home *** CD-ROM | disk | FTP | other *** search
/ Enter 2001 April / EnterCD4.iso / Update / SQL Server SP3 / sql70sp3i.exe / INSTALL / procsyst.sql < prev    next >
Encoding:
Text File  |  2000-09-06  |  511.5 KB  |  19,074 lines

  1. /*
  2. ** ProcSyst.SQL  --- Copyright Microsoft 1994-1998
  3. ** All Rights Reserved.
  4. ** Use, duplication, or disclosure by the United States Government
  5. ** is subject to restrictions as set forth in subdivision (c) (1) (ii)
  6. ** of the Rights in Technical Data and Computer Software clause
  7. ** at CFR 252.227-7013. Microsoft, Inc. One Microsoft Way, Redmond WA
  8. ** 98052.
  9. */
  10.  
  11. go
  12. use master
  13. go
  14. checkpoint
  15. go
  16. set nocount on
  17. set implicit_transactions off
  18. set ansi_nulls off
  19. go
  20.  
  21. declare @vdt varchar(99)
  22. select  @vdt = convert(varchar,getdate(),113)
  23. raiserror('Starting Install\ProcSyst.SQL at  %s',0,1,@vdt) with nowait
  24. go
  25.  
  26. print ' '
  27. print 'Making sure that updates to system tables are allowed.'
  28. go
  29.  
  30. declare  @int1            integer
  31. --dbcc getvalue('current_version')  --1=4.21A ,400-406=6.0 ,407-?=6.5, currently 408=7.0
  32. --select @dbcc_current_version = @@error
  33.  
  34. if (     object_id('sp_configure','P') IS NOT NULL
  35.     AND  1 <> (select value from syscurconfigs where config = 102)
  36.    )
  37.     begin                        --Query tree compatible
  38.     exec @int1 = sp_configure 'allow updates',1
  39.     if @@error <> 0 or @int1 <> 0
  40.         raiserror('Bad sp_configure exec at top of ProcSyst.SQL, killing spid.'
  41.             ,22,127) with log
  42.     reconfigure with override
  43.     end
  44. go
  45.  
  46. ---- Make sure server was started in single user mode or that sp_configure was used
  47. ----    to enable updates to system tables.
  48.  
  49. if (select value from syscurconfigs where config = 102) <> 1
  50.     raiserror('Cannot run ProcSyst.SQL unless updates to system tables are enabled.  Shutdown server and restart with the ''-m'' option or use sp_configure to enable updates to system tables.'
  51.             ,22,127) with log
  52. go
  53.  
  54. exec sp_MS_upd_sysobj_category 1  --Capture now_datetime for use below.
  55.  
  56. go
  57.  
  58. print ' '
  59. print 'Dropping procedures that will be (re)created.'
  60. go
  61.  
  62. ----- ---
  63.  
  64. if object_id('sp_fallback_activate_svr','P') IS NOT NULL
  65.     drop procedure sp_fallback_activate_svr
  66. if object_id('sp_fallback_activate_svr_db','P') IS NOT NULL
  67.     drop procedure sp_fallback_activate_svr_db
  68.  
  69. if object_id('sp_fallback_deactivate_svr','P') IS NOT NULL
  70.     drop procedure sp_fallback_deactivate_svr
  71. if object_id('sp_fallback_deactivate_svr_db','P') IS NOT NULL
  72.     drop procedure sp_fallback_deactivate_svr_db
  73.  
  74. if object_id('sp_fallback_enroll_svr_db','P') IS NOT NULL
  75.     drop procedure sp_fallback_enroll_svr_db
  76.  
  77. if object_id('sp_fallback_help','P') IS NOT NULL
  78.     drop procedure sp_fallback_help
  79.  
  80. if object_id('sp_fallback_help_db_dev','P') IS NOT NULL
  81.     drop procedure sp_fallback_help_db_dev
  82.  
  83. if object_id('sp_fallback_MS_enroll_db','P') IS NOT NULL
  84.     drop procedure sp_fallback_MS_enroll_db
  85.  
  86. if object_id('sp_fallback_MS_enroll_dev','P') IS NOT NULL
  87.     drop procedure sp_fallback_MS_enroll_dev
  88.  
  89. if object_id('sp_fallback_MS_enroll_usg','P') IS NOT NULL
  90.     drop procedure sp_fallback_MS_enroll_usg
  91.  
  92. if object_id('sp_fallback_MS_sel_fb_svr','P') IS NOT NULL
  93.     drop procedure sp_fallback_MS_sel_fb_svr
  94.  
  95. if object_id('sp_fallback_MS_verify_ri','P') IS NOT NULL
  96.     drop procedure sp_fallback_MS_verify_ri
  97.  
  98. if object_id('sp_fallback_permanent_svr','P') IS NOT NULL
  99.     drop procedure sp_fallback_permanent_svr
  100.  
  101. if object_id('sp_fallback_upd_dev_drive','P') IS NOT NULL
  102.     drop procedure sp_fallback_upd_dev_drive
  103.  
  104. if object_id('sp_fallback_withdraw_svr_db','P') IS NOT NULL
  105.     drop procedure sp_fallback_withdraw_svr_db
  106.  
  107.  
  108.  
  109. go
  110. ------------------------------------------------------------
  111.  
  112. if object_id('sp_a_count_bits_on','P') IS NOT NULL
  113.              drop procedure sp_a_count_bits_on
  114.  
  115. if object_id('sp_abort_xact','P') IS NOT NULL
  116.     drop procedure sp_abort_xact
  117.  
  118. if object_id('sp_addextendedproc','P') IS NOT NULL
  119.     drop procedure sp_addextendedproc
  120.  
  121. if object_id('sp_addmessage','P') IS NOT NULL
  122.     drop procedure sp_addmessage
  123.  
  124. if object_id('sp_addremotelogin','P') IS NOT NULL
  125.     drop procedure sp_addremotelogin
  126.  
  127. if object_id('sp_addsegment','P') IS NOT NULL
  128.     drop procedure sp_addsegment
  129. go
  130.  
  131. checkpoint
  132. go
  133.  
  134. if object_id('sp_addtype','P') IS NOT NULL
  135.     drop procedure sp_addtype
  136.  
  137. if object_id('sp_addumpdevice','P') IS NOT NULL
  138.     drop procedure sp_addumpdevice
  139.  
  140. if object_id('sp_altermessage','P') IS NOT NULL
  141.         drop procedure sp_altermessage
  142.  
  143. if object_id('sp_attach_db','P') IS NOT NULL
  144.     drop procedure sp_attach_db
  145.  
  146. if object_id('sp_attach_single_file_db','P') IS NOT NULL
  147.     drop procedure sp_attach_single_file_db
  148. go
  149.  
  150. if object_id('sp_bindefault','P') IS NOT NULL
  151.     drop procedure sp_bindefault
  152.  
  153. if object_id('sp_bindrule','P') IS NOT NULL
  154.     drop procedure sp_bindrule
  155.  
  156. if object_id('sp_blockcnt','P') IS NOT NULL
  157.     drop procedure sp_blockcnt
  158.  
  159. if object_id('sp_checknames','P') IS NOT NULL
  160.     drop procedure sp_checknames
  161.  
  162. if object_id('sp_commit_xact','P') IS NOT NULL
  163.     drop procedure sp_commit_xact
  164. go
  165.  
  166. if object_id('sp_configure','P') IS NOT NULL
  167.     drop procedure sp_configure
  168.  
  169. if object_id('sp_create_removable','P') IS NOT NULL
  170.     drop procedure sp_create_removable
  171.  
  172. if object_id('sp_createstats','P') IS NOT NULL
  173.     drop procedure sp_createstats
  174.  
  175. if object_id('sp_cycle_errorlog','P') IS NOT NULL
  176.     drop procedure sp_cycle_errorlog
  177.  
  178. if object_id('sp_certify_removable','P') IS NOT NULL
  179.     drop procedure sp_certify_removable
  180.  
  181. if object_id('sp_check_removable','P') IS NOT NULL
  182.     drop procedure sp_check_removable
  183.  
  184. if object_id('sp_cnst_csr','P') IS NOT NULL
  185.     drop procedure sp_cnst_csr
  186.  
  187. if object_id('sp_coalesce_fragments','P') IS NOT NULL
  188.     drop procedure sp_coalesce_fragments
  189.  
  190. if object_id('sp_dboption','P') IS NOT NULL
  191.     drop procedure sp_dboption
  192.  
  193. if object_id('sp_dbcmptlevel','P') IS NOT NULL
  194.     drop procedure sp_dbcmptlevel
  195.  
  196. if object_id('sp_dbremove','P') IS NOT NULL
  197.     drop procedure sp_dbremove
  198.  
  199. if object_id('sp_depends','P') IS NOT NULL
  200.     drop procedure sp_depends
  201.  
  202. if object_id('sp_detach_db','P') IS NOT NULL
  203.     drop procedure sp_detach_db
  204.  
  205. if object_id('sp_diskdefault','P') IS NOT NULL
  206.     drop procedure sp_diskdefault
  207. go
  208.  
  209. if object_id('sp_dropdevice','P') IS NOT NULL
  210.     drop procedure sp_dropdevice
  211.  
  212. if object_id('sp_dropdumpdevice','P') IS NOT NULL
  213.     drop procedure sp_dropdumpdevice
  214.  
  215. if object_id('sp_dropextendedproc','P') IS NOT NULL
  216.     drop procedure sp_dropextendedproc
  217. go
  218.  
  219. if object_id('sp_dropmessage','P') IS NOT NULL
  220.     drop procedure sp_dropmessage
  221.  
  222. if object_id('sp_droptype','P') IS NOT NULL
  223.     drop procedure sp_droptype
  224.  
  225. if object_id('sp_dropremotelogin','P') IS NOT NULL
  226.     drop procedure sp_dropremotelogin
  227.  
  228. if object_id('sp_dropsegment','P') IS NOT NULL
  229.     drop procedure sp_dropsegment
  230.  
  231. if object_id('sp_extendsegment','P') IS NOT NULL
  232.     drop procedure sp_extendsegment
  233. go
  234.  
  235. if object_id('sp_help','P') IS NOT NULL
  236.     drop procedure sp_help
  237.  
  238. if object_id('sp_help_revdatabase','P') IS NOT NULL
  239.              drop procedure sp_help_revdatabase
  240.  
  241. if object_id('sp_helpconstraint','P') IS NOT NULL
  242.     drop procedure sp_helpconstraint
  243.  
  244. if object_id('sp_helpdb','P') IS NOT NULL
  245.     drop procedure sp_helpdb
  246.  
  247. if object_id('sp_helpdevice','P') IS NOT NULL
  248.     drop procedure sp_helpdevice
  249.  
  250. if object_id('sp_helpextendedproc','P') IS NOT NULL
  251.     drop procedure sp_helpextendedproc
  252.  
  253. if object_id('sp_helpfile','P') IS NOT NULL
  254.     drop procedure sp_helpfile
  255.  
  256. if object_id('sp_helpfilegroup','P') IS NOT NULL
  257.     drop procedure sp_helpfilegroup
  258.  
  259. if object_id('sp_helpgroup','P') IS NOT NULL
  260.     drop procedure sp_helpgroup
  261.  
  262. if object_id('sp_helpindex','P') IS NOT NULL
  263.     drop procedure sp_helpindex
  264. go
  265.  
  266. checkpoint
  267. go
  268.  
  269. if object_id('sp_helplanguage','P') IS NOT NULL
  270.     drop procedure sp_helplanguage
  271.  
  272. if object_id('sp_helplog','P') IS NOT NULL
  273.     drop procedure sp_helplog
  274.  
  275. if object_id('sp_helplogins','P') IS NOT NULL
  276.              drop procedure sp_helplogins
  277.  
  278. if object_id('sp_helprotect','P') IS NOT NULL
  279.     drop procedure sp_helprotect
  280.  
  281. if object_id('sp_helptext','P') IS NOT NULL
  282.     drop procedure sp_helptext
  283.  
  284. if object_id('sp_helpuser','P') IS NOT NULL
  285.     drop procedure sp_helpuser
  286.  
  287. if object_id('sp_helpremotelogin','P') IS NOT NULL
  288.     drop procedure sp_helpremotelogin
  289.  
  290. if object_id('sp_helpsegment','P') IS NOT NULL
  291.     drop procedure sp_helpsegment
  292.  
  293. if object_id('sp_helpsort','P') IS NOT NULL
  294.     drop procedure sp_helpsort
  295.  
  296. if object_id('sp_helpsql','P') IS NOT NULL
  297.     drop procedure sp_helpsql
  298.  
  299. if object_id('sp_helpstartup','P') IS NOT NULL
  300.     drop procedure sp_helpstartup
  301.  
  302. if object_id('sp_indexoption','P') IS NOT NULL
  303.     drop procedure sp_indexoption
  304.  
  305. if object_id('sp_lock','P') IS NOT NULL
  306.     drop procedure sp_lock
  307. go
  308.  
  309. if object_id('sp_logdevice','P') IS NOT NULL
  310.     drop procedure sp_logdevice
  311.  
  312. if object_id('sp_makestartup','P') IS NOT NULL
  313.     drop procedure sp_makestartup
  314.  
  315. if object_id('sp_monitor','P') IS NOT NULL
  316.     drop procedure sp_monitor
  317.  
  318. if object_id('sp_namecrack','P') IS NOT NULL
  319.     drop procedure sp_namecrack
  320.  
  321. if object_id('sp_namecrack_qi','P') IS NOT NULL
  322.     drop procedure sp_namecrack_qi
  323.  
  324. if object_id('sp_objectfilegroup','P') IS NOT NULL
  325.     drop procedure sp_objectfilegroup
  326.  
  327. if object_id('sp_placeobject','P') IS NOT NULL
  328.     drop procedure sp_placeobject
  329.  
  330. if object_id('sp_probe_xact','P') IS NOT NULL
  331.     drop procedure sp_probe_xact
  332.  
  333. if object_id('sp_procoption','P') IS NOT NULL
  334.     drop procedure sp_procoption
  335.  
  336. if object_id('sp_processmail','P') IS NOT NULL
  337.     drop procedure sp_processmail
  338. go
  339.  
  340. if object_id('sp_recompile','P') IS NOT NULL
  341.     drop procedure sp_recompile
  342.  
  343. if object_id('sp_remoteoption','P') IS NOT NULL
  344.     drop procedure sp_remoteoption
  345.  
  346. if object_id('sp_remove_xact','P') IS NOT NULL
  347.     drop procedure sp_remove_xact
  348.  
  349. if object_id('sp_rename','P') IS NOT NULL
  350.     drop procedure sp_rename
  351.  
  352. if object_id('sp_renamedb','P') IS NOT NULL
  353.     drop procedure sp_renamedb
  354.  
  355. if object_id('sp_remove_tempdb_file','P') IS NOT NULL
  356.         drop procedure sp_remove_tempdb_file
  357.  
  358. if object_id('sp_resetstatus','P') IS NOT NULL
  359.    drop procedure sp_resetstatus
  360. go
  361.  
  362. if object_id('sp_add_file_recover_suspect_db','P') IS NOT NULL
  363.     drop procedure sp_add_file_recover_suspect_db
  364.  
  365. if object_id('sp_add_data_file_recover_suspect_db','P') IS NOT NULL
  366.     drop procedure sp_add_data_file_recover_suspect_db
  367.  
  368. if object_id('sp_add_log_file_recover_suspect_db','P') IS NOT NULL
  369.     drop procedure sp_add_log_file_recover_suspect_db
  370. go
  371.  
  372. if object_id('sp_scan_xact','P') IS NOT NULL
  373.     drop procedure sp_scan_xact
  374.  
  375. if object_id('sp_spaceused','P') IS NOT NULL
  376.     drop procedure sp_spaceused
  377.  
  378. if object_id('sp_checktabletempsize', 'P') IS NOT NULL
  379.     drop procedure sp_checktabletempsize
  380.  
  381. if object_id('sp_checkdbtempsize', 'P') IS NOT NULL
  382.     drop procedure sp_checkdbtempsize
  383.  
  384. if object_id('sp_sqlexec','P') IS NOT NULL
  385.     drop procedure sp_sqlexec
  386.  
  387. if object_id('sp_start_xact','P') IS NOT NULL
  388.     drop procedure sp_start_xact
  389.  
  390. if object_id('sp_stat_xact','P') IS NOT NULL
  391.     drop procedure sp_stat_xact
  392. go
  393.  
  394. if object_id('sp_tableoption','P') IS NOT NULL
  395.     drop procedure sp_tableoption
  396.  
  397. if object_id('sp_tempdbspace','P') IS NOT NULL
  398.     drop procedure sp_tempdbspace
  399.  
  400. if object_id('sp_unbindefault','P') IS NOT NULL
  401.     drop procedure sp_unbindefault
  402.  
  403. if object_id('sp_unbindrule','P') IS NOT NULL
  404.     drop procedure sp_unbindrule
  405.  
  406. if object_id('sp_unmakestartup','P') IS NOT NULL
  407.     drop procedure sp_unmakestartup
  408.  
  409.  
  410. if object_id('sp_user_counter1','P') IS NOT NULL
  411.         drop procedure sp_user_counter1
  412. if object_id('sp_user_counter2','P') IS NOT NULL
  413.         drop procedure sp_user_counter2
  414. if object_id('sp_user_counter3','P') IS NOT NULL
  415.         drop procedure sp_user_counter3
  416. if object_id('sp_user_counter4','P') IS NOT NULL
  417.         drop procedure sp_user_counter4
  418. if object_id('sp_user_counter5','P') IS NOT NULL
  419.         drop procedure sp_user_counter5
  420. if object_id('sp_user_counter6','P') IS NOT NULL
  421.         drop procedure sp_user_counter6
  422. if object_id('sp_user_counter7','P') IS NOT NULL
  423.         drop procedure sp_user_counter7
  424. if object_id('sp_user_counter8','P') IS NOT NULL
  425.         drop procedure sp_user_counter8
  426. if object_id('sp_user_counter9','P') IS NOT NULL
  427.         drop procedure sp_user_counter9
  428. if object_id('sp_user_counter10','P') IS NOT NULL
  429.         drop procedure sp_user_counter10
  430. go
  431.  
  432.  
  433. if object_id('sp_validaltlang','P') IS NOT NULL
  434.     drop procedure sp_validaltlang
  435.  
  436. if object_id('sp_validlang','P') IS NOT NULL
  437.     drop procedure sp_validlang
  438.  
  439. if object_id('sp_validname','P') IS NOT NULL
  440.     drop procedure sp_validname
  441.  
  442. if object_id('sp_who','P') IS NOT NULL
  443.     drop procedure sp_who
  444.  
  445. if object_id('sp_who2','P') IS NOT NULL
  446.     drop procedure sp_who2
  447. go
  448.  
  449. if object_id('sp_updatestats','P') IS NOT NULL
  450.     drop procedure sp_updatestats 
  451. go
  452.  
  453. if object_id('sp_autostats','P') IS NOT NULL
  454.     drop procedure sp_autostats 
  455. go
  456.  
  457. if object_id('sp_helptrigger','P') IS NOT NULL
  458.     drop procedure sp_helptrigger 
  459. go
  460.  
  461. if object_id('sp_fixindex','P') IS NOT NULL
  462.     drop procedure sp_fixindex 
  463. go
  464.  
  465. if object_id('MS_sqlctrs_users','P') IS NOT NULL
  466.     drop proc MS_sqlctrs_users
  467.  
  468. if object_id('sp_MSget_current_activity','P') IS NOT NULL
  469.     drop procedure sp_MSget_current_activity
  470.  
  471. if object_id('sp_MSset_current_activity','P') IS NOT NULL
  472.     drop procedure sp_MSset_current_activity
  473.  
  474. checkpoint
  475. go
  476.  
  477.  
  478. -------------------------
  479.  -- create XP early for sysdepends
  480. raiserror('Special section to create extended procs early for sysdepends...',0,1)
  481. go
  482.  
  483.  
  484. raiserror(15339,-1,-1,'sp_dropextendedproc')
  485. go
  486. create procedure sp_dropextendedproc --- 1996/08/30 20:13
  487. @functname nvarchar(517) -- name of function
  488. as
  489. /*
  490. **  If we're in a transaction, disallow the dropping of the
  491. **  extended stored procedure.
  492. */
  493. set implicit_transactions off
  494. if @@trancount > 0
  495.     begin
  496.         raiserror(15002,-1,-1,'sp_dropextendedproc')
  497.         return (1)
  498.     end
  499.  
  500. /*
  501. ** Drop the extended procedure mapping.
  502. */
  503. dbcc dropextendedproc( @functname )
  504. return (0) -- sp_dropextendedproc
  505. go
  506.  
  507.  
  508.  
  509. raiserror(15339,-1,-1,'sp_addextendedproc')
  510. go
  511. create procedure sp_addextendedproc --- 1996/08/30 20:13
  512. @functname nvarchar(517),        /* (owner.)name of function to call */
  513. @dllname varchar(255)        /* name of DLL containing function */
  514. as
  515. /*
  516. **  If we're in a transaction, disallow the addition of the
  517. **  extended stored procedure.
  518. */
  519. set implicit_transactions off
  520. if @@trancount > 0
  521. begin
  522.     raiserror(15002,-1,-1,'sp_addextendedproc')
  523.     return (1)
  524. end
  525.  
  526. /*
  527. ** Create the extended procedure mapping.
  528. */
  529. dbcc addextendedproc( @functname, @dllname)
  530. return (0) -- sp_addextendedproc
  531. go
  532.  
  533.  
  534. raiserror(15339,-1,-1,'sp_helpextendedproc')
  535. go
  536. create procedure sp_helpextendedproc --- 1996/08/14 15:53
  537. @funcname sysname = NULL
  538. as
  539.  
  540. set nocount on
  541.  
  542. if (select count(*) from master.dbo.sysobjects where xtype = 'X ') = 0
  543.     begin
  544.         raiserror(15326,-1,-1)
  545.         return (0)
  546.     end
  547.  
  548.  
  549. if @funcname is not null
  550. begin
  551.     /*
  552.     **  Make sure the function name exists
  553.     */
  554.     if not exists (select * from master.dbo.sysobjects
  555.             where xtype = 'X '
  556.               and name = @funcname)
  557.     begin
  558.         raiserror(15019,-1,-1,@funcname)
  559.         return (1)
  560.     end
  561.     /*print out select function name info*/
  562.     select distinct name = o.name, dll = substring(c.text,1,255)
  563.     from master.dbo.sysobjects o, master.dbo.syscomments c
  564.     where o.id = c.id
  565.         and o.name = @funcname
  566.         and o.xtype = 'X '
  567.     order by o.name
  568. end
  569. else
  570. /*
  571. **  or print out all function name info
  572. */
  573. select distinct name = o.name, dll = substring(c.text,1,255)
  574.     from master.dbo.sysobjects o, master.dbo.syscomments c
  575.     where o.id = c.id
  576.         and o.xtype = 'X '
  577.     order by o.name
  578.  
  579. return (0) -- sp_helpextendedproc
  580. go
  581.  
  582.  
  583. ---------------------------------------------------------------
  584. raiserror('Now done creating the general system stored procs.  Start with miscellaneous tasks like xp_ and grants.',0,1)
  585. ---------------------------------------------------------------
  586. go
  587.  
  588. ---- Drop extended procs if they already exist now that sp_dropextendedproc has been created.
  589.  
  590. print ' '
  591. print 'Dropping any existing extended stored procedures.'
  592. go
  593.  
  594. if object_id('xp_addattach','X') IS NOT NULL
  595.     exec sp_dropextendedproc 'xp_addattach'
  596.  
  597. if object_id('xp_addmsgline','X') IS NOT NULL
  598.     exec sp_dropextendedproc 'xp_addmsgline'
  599.  
  600. if object_id('xp_cmdshell','X') IS NOT NULL
  601.     exec sp_dropextendedproc 'xp_cmdshell'
  602.  
  603. if object_id('sp_cursor','X') IS NOT NULL
  604.     exec sp_dropextendedproc 'sp_cursor'
  605.  
  606. if object_id('sp_cursorclose','X') IS NOT NULL
  607.     exec sp_dropextendedproc 'sp_cursorclose'
  608.  
  609. if object_id('sp_cursorfetch','X') IS NOT NULL
  610.     exec sp_dropextendedproc 'sp_cursorfetch'
  611.  
  612. if object_id('sp_cursoropen','X') IS NOT NULL
  613.     exec sp_dropextendedproc 'sp_cursoropen'
  614.  
  615. if object_id('sp_cursoroption','X') IS NOT NULL
  616.     exec sp_dropextendedproc 'sp_cursoroption'
  617.  
  618. if object_id('xp_deletemail','X') IS NOT NULL
  619.     exec sp_dropextendedproc 'xp_deletemail'
  620.  
  621. if object_id('xp_enumgroups','X') IS NOT NULL
  622.     exec sp_dropextendedproc 'xp_enumgroups'
  623.  
  624. if object_id('xp_findnextmsg','X') IS NOT NULL
  625.     exec sp_dropextendedproc 'xp_findnextmsg'
  626.  
  627. if object_id('xp_logevent','X') IS NOT NULL
  628.     exec sp_dropextendedproc 'xp_logevent'
  629.  
  630. if object_id('xp_loginconfig','X') IS NOT NULL
  631.     exec sp_dropextendedproc 'xp_loginconfig'
  632.  
  633. if object_id('xp_logininfo','X') IS NOT NULL
  634.     exec sp_dropextendedproc 'xp_logininfo'
  635.  
  636. if object_id('xp_loginmail','X') IS NOT NULL
  637.     exec sp_dropextendedproc 'xp_loginmail'
  638.  
  639. if object_id('xp_logoffmail','X') IS NOT NULL
  640.     exec sp_dropextendedproc 'xp_logoffmail'
  641.  
  642. if object_id('xp_mailproclist','X') IS NOT NULL
  643.     exec sp_dropextendedproc 'xp_mailproclist'
  644.  
  645. if object_id('xp_msver','X') IS NOT NULL
  646.     exec sp_dropextendedproc 'xp_msver'
  647.  
  648. if object_id('xp_prepmsg','X') IS NOT NULL
  649.     exec sp_dropextendedproc 'xp_prepmsg'
  650.  
  651. if object_id('xp_readmail','X') IS NOT NULL
  652.     exec sp_dropextendedproc 'xp_readmail'
  653.  
  654. if object_id('xp_sendmail','X') IS NOT NULL
  655.     exec sp_dropextendedproc 'xp_sendmail'
  656.  
  657. if object_id('xp_sendmsg','X') IS NOT NULL
  658.     exec sp_dropextendedproc 'xp_sendmsg'
  659.  
  660. if object_id('xp_sprintf','X') IS NOT NULL
  661.     exec sp_dropextendedproc 'xp_sprintf'
  662.  
  663. if object_id('xp_sscanf','X') IS NOT NULL
  664.     exec sp_dropextendedproc 'xp_sscanf'
  665.  
  666. if object_id('xp_startmail','X') IS NOT NULL
  667.     exec sp_dropextendedproc 'xp_startmail'
  668.  
  669. if object_id('xp_stopmail','X') IS NOT NULL
  670.     exec sp_dropextendedproc 'xp_stopmail'
  671. go
  672.  
  673. if object_id('xp_unc_to_drive','X') IS NOT NULL
  674.     exec sp_dropextendedproc 'xp_unc_to_drive'
  675.  
  676. if object_id('sp_bindsession','X') IS NOT NULL
  677.     exec sp_dropextendedproc 'sp_bindsession'
  678.  
  679. if object_id('sp_getbindtoken','X') IS NOT NULL
  680.     exec sp_dropextendedproc 'sp_getbindtoken'
  681.  
  682. if object_id('sp_createorphan','X') IS NOT NULL
  683.     exec sp_dropextendedproc 'sp_createorphan'
  684.  
  685. if object_id('sp_droporphans','X') IS NOT NULL
  686.     exec sp_dropextendedproc 'sp_droporphans'
  687.  
  688. if object_id('sp_sdidebug','X') IS NOT NULL
  689.     exec sp_dropextendedproc 'sp_sdidebug'
  690.  
  691. if object_id('sp_executesql','X') IS NOT NULL
  692.     exec sp_dropextendedproc 'sp_executesql'
  693.  
  694. if object_id('sp_stmtpermissions','X') IS NOT NULL
  695.     exec sp_dropextendedproc 'sp_stmtpermissions'
  696.  
  697. if object_id('sp_objpermissions','X') IS NOT NULL
  698.     exec sp_dropextendedproc 'sp_objpermissions'
  699.  
  700. if object_id('sp_prepare','X') IS NOT NULL
  701.     exec sp_dropextendedproc 'sp_prepare'
  702.  
  703. if object_id('sp_execute','X') IS NOT NULL
  704.     exec sp_dropextendedproc 'sp_execute'
  705.  
  706. if object_id('sp_unprepare','X') IS NOT NULL
  707.     exec sp_dropextendedproc 'sp_unprepare'
  708.  
  709. if object_id('sp_cursorprepare','X') IS NOT NULL
  710.     exec sp_dropextendedproc 'sp_cursorprepare'
  711.  
  712. if object_id('sp_cursorexecute','X') IS NOT NULL
  713.     exec sp_dropextendedproc 'sp_cursorexecute'
  714.  
  715. if object_id('sp_cursorunprepare','X') IS NOT NULL
  716.     exec sp_dropextendedproc 'sp_cursorunprepare'
  717.  
  718. if object_id('sp_reset_connection','X') IS NOT NULL
  719.     exec sp_dropextendedproc 'sp_reset_connection'
  720. go
  721.  
  722.  
  723. -- Add extended stored procedures.
  724. print ' '
  725. print 'Adding extended stored procedures.'
  726. go
  727.  
  728. execute sp_addextendedproc 'xp_cmdshell'    ,'xpsql70.dll'
  729. execute sp_addextendedproc 'xp_logevent'    ,'xpsql70.dll'
  730. execute sp_addextendedproc 'xp_sprintf'        ,'xpsql70.dll'
  731. execute sp_addextendedproc 'xp_sscanf'        ,'xpsql70.dll'
  732. execute sp_addextendedproc 'xp_unc_to_drive'    ,'xpsql70.dll'
  733. execute sp_addextendedproc 'xp_msver'        ,'xpsql70.dll'
  734. execute sp_addextendedproc 'xp_enumgroups'    ,'xplog70.dll'
  735. go
  736.  
  737. -- Add mail enabling extended procedures
  738. --
  739. execute sp_addextendedproc 'xp_startmail'    ,'sqlmap70.dll'
  740. execute sp_addextendedproc 'xp_stopmail'    ,'sqlmap70.dll'
  741. execute sp_addextendedproc 'xp_sendmail'    ,'sqlmap70.dll'
  742. execute sp_addextendedproc 'xp_deletemail'    ,'sqlmap70.dll'
  743. execute sp_addextendedproc 'xp_findnextmsg'    ,'sqlmap70.dll'
  744. execute sp_addextendedproc 'xp_readmail'    ,'sqlmap70.dll'
  745. go
  746.  
  747. --Add extended stored procedures for NT integrated login security.
  748. --
  749. execute sp_addextendedproc 'xp_loginconfig'    ,'xplog70.dll'
  750. go
  751.  
  752. -- Add extended stored procedures for cursor support.
  753. --
  754. execute sp_addextendedproc 'sp_cursor'        ,'(server internal)'
  755. execute sp_addextendedproc 'sp_cursorclose'    ,'(server internal)'
  756. execute sp_addextendedproc 'sp_cursorfetch'    ,'(server internal)'
  757. execute sp_addextendedproc 'sp_cursoropen'    ,'(server internal)'
  758. execute sp_addextendedproc 'sp_cursoroption'    ,'(server internal)'
  759. go
  760.  
  761. -- Add extended stored procedures for bound session support.
  762. --
  763. execute sp_addextendedproc 'sp_bindsession'    ,'(server internal)'
  764. execute sp_addextendedproc 'sp_getbindtoken'    ,'(server internal)'
  765. go
  766.  
  767. -- Add extended stored procedures for orphaned text support for ODBC
  768. --
  769. execute sp_addextendedproc 'sp_createorphan' ,'(server internal)'
  770. execute sp_addextendedproc 'sp_droporphans' ,'(server internal)'
  771. go
  772.  
  773. -- This xproc will be used for SQL debugging and will be invoked either via RPC or SQL language.
  774. --
  775. execute sp_addextendedproc 'sp_sdidebug'    ,'(server internal)'
  776. go
  777.  
  778. -- This xproc will be used for server support for Prepare-Execute
  779. --
  780. execute sp_addextendedproc 'sp_executesql'    ,'(server internal)'
  781. go
  782.  
  783. -- Starfter requested security proc
  784. --
  785. execute sp_addextendedproc 'sp_prepare'    ,'(server internal)'
  786. go
  787. execute sp_addextendedproc 'sp_execute'    ,'(server internal)'
  788. go
  789. execute sp_addextendedproc 'sp_unprepare'    ,'(server internal)'
  790. go
  791. execute sp_addextendedproc 'sp_cursorprepare'    ,'(server internal)'
  792. go
  793. execute sp_addextendedproc 'sp_cursorexecute'    ,'(server internal)'
  794. go
  795. execute sp_addextendedproc 'sp_cursorunprepare'    ,'(server internal)'
  796. go
  797.  
  798. -- This xproc will be used for server support for connection-caching
  799. --
  800. execute sp_addextendedproc 'sp_reset_connection','(server internal)'
  801. go
  802.  
  803.  
  804. -- UPDATE A VIEW'S METADATA TO REFLECT CHANGES IN UNDERLYING TABLES --
  805. if object_id('sp_refreshview','X') IS NOT NULL
  806.     exec sp_dropextendedproc 'sp_refreshview'
  807. execute sp_addextendedproc 'sp_refreshview','(server internal)'
  808. grant execute on sp_refreshview to public
  809. go
  810.  
  811.  
  812. -------------------------------------
  813. raiserror('Creating the general purpose System Stored Procedures ....',0,1)
  814. -------------------------------------
  815. go
  816.  
  817.  
  818. raiserror(15339,-1,-1,'sp_user_counter1 - N')
  819. go
  820.  
  821. create proc sp_user_counter1 @newvalue int as
  822. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 1', @newvalue)
  823. go
  824. create proc sp_user_counter2 @newvalue int as
  825. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 2', @newvalue)
  826. go
  827. create proc sp_user_counter3 @newvalue int as
  828. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 3', @newvalue)
  829. go
  830. create proc sp_user_counter4 @newvalue int as
  831. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 4', @newvalue)
  832. go
  833. create proc sp_user_counter5 @newvalue int as
  834. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 5', @newvalue)
  835. go
  836. create proc sp_user_counter6 @newvalue int as
  837. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 6', @newvalue)
  838. go
  839. create proc sp_user_counter7 @newvalue int as
  840. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 7', @newvalue)
  841. go
  842. create proc sp_user_counter8 @newvalue int as
  843. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 8', @newvalue)
  844. go
  845. create proc sp_user_counter9 @newvalue int as
  846. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 9', @newvalue)
  847. go
  848. create proc sp_user_counter10 @newvalue int as
  849. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 10', @newvalue)
  850. go
  851.  
  852.  
  853. --perfmon
  854. raiserror(15339,-1,-1,'sp_blockcnt')
  855. go
  856. create procedure sp_blockcnt --- 1996/04/08 00:00
  857. as
  858. select blockedusers=count(*) from master.dbo.sysprocesses where blocked <> 0
  859. go
  860.  
  861.  
  862.  
  863. --new query to watch max tempdbspace from perfmon
  864. raiserror(15339,-1,-1,'sp_tempdbspace')
  865. go
  866. create proc sp_tempdbspace --- 1996/04/08 00:00
  867. as
  868.  
  869. declare @dbsize dec(15,0)
  870. declare @freespace dec(15,0)
  871. declare @spaceused dec(15,0)
  872.  
  873. select @dbsize = sum(convert(dec(15),size))
  874.                from tempdb.dbo.sysfiles
  875.  
  876. select  database_name = 'tempdb',
  877.                database_size = (@dbsize / 128),
  878.            spaceused=(select (sum(convert(dec(15),reserved))/128)
  879.                    from tempdb..sysindexes
  880.         where indid in (0, 1, 255))
  881. go
  882.  
  883.  
  884.  
  885.  
  886. raiserror(15339,-1,-1,'sp_dboption')
  887. go
  888. /*ANSI_NULLS ON  for creation of sp_dboption*/
  889. set ansi_nulls on
  890. go
  891. create procedure sp_dboption  -- 1996/03/15 12:51
  892. @dbname sysname = NULL,     /* database name to change */
  893. @optname varchar(35) = NULL,  /* option name to turn on/off */
  894. @optvalue varchar(10) = NULL  /* true or false */
  895. as
  896.  
  897. set nocount    on
  898.  
  899. declare @dbid int         /* dbid of the database */
  900. declare @dbsid varbinary(85)           /* id of the owner of the database */
  901. declare @statvalue int     /* number of status option */
  902. declare @statvalue2 int     /* number of status2 option */
  903. declare @catvalue int     /* number of category option */
  904. declare @optcount int      /* number of options like @optname */
  905. declare @allstatopts int    /* bit map off all options stored in sysdatqabases.status 
  906.                             ** that can be set by sp_dboption. */
  907. declare @alloptopts int    /* bit map off all options stored in sysdatqabases.status 
  908.                             ** that can be set by sp_dboption. */
  909. declare @allcatopts int    /* bit map off all options stored in sysdatqabases.category 
  910.                             ** that can be set by sp_dboption. */
  911. declare @exec_stmt nvarchar(550)
  912. declare @devname sysname
  913. declare @cur_dbname sysname
  914. declare @ret_code int
  915. declare @int1 int
  916. ,@opt_autoclose int
  917. ,@opt_trunclogonchkpt int
  918. ,@opt_tornpage int
  919. ,@fulloptname varchar(35)
  920. ,@orig_db_status int
  921. ,@orig_db_status2 int
  922. ,@opt_bit_singleuser integer
  923. ,@opt_catnull integer
  924. ,@opt_ansinulldefault integer
  925. ,@opt_defaulttolocalcursor integer
  926. ,@opt_selectintobulkcopy integer
  927. ,@opt_recursivetriggers integer
  928. ,@opt_offline integer
  929. ,@opt_quotedid integer
  930. ,@opt_cursorcommitclose integer
  931. ,@opt_compnull integer
  932. ,@opt_ansiwarnings integer
  933. ,@opt_autocrtstats integer
  934. ,@opt_autoupdstats integer
  935. ,@returncode    int
  936.  
  937. /*
  938. **  If no @dbname given, just list the possible dboptions.
  939. **  Only certain status bits may be set or cleared by sp_dboption.
  940. */
  941.  
  942. /*
  943. ** Get bitmap of all options that can be set by sp_dboption.
  944. */
  945. select @allstatopts=number from master.dbo.spt_values where type = 'D'
  946.    and name = 'ALL SETTABLE OPTIONS'
  947.  
  948. select @allcatopts=number from master.dbo.spt_values where type = 'DC'
  949.    and name = 'ALL SETTABLE OPTIONS'
  950.  
  951. select @alloptopts=number from master.dbo.spt_values where type = 'D2'
  952.    and name = 'ALL SETTABLE OPTIONS'
  953.  
  954. if @dbname is null
  955. begin
  956.    select 'Settable database options:' = name
  957.       from master.dbo.spt_values
  958.       where (type = 'D' 
  959.             and number & @allstatopts <> 0
  960.             and number not in (0,@allstatopts))  /* Eliminate non-option entries */
  961.          or (type = 'DC'
  962.             and number & @allcatopts <> 0
  963.             and number not in (0,@allcatopts))
  964.          or (type = 'D2'
  965.             and number & @alloptopts <> 0
  966.             and number not in (0,@alloptopts))
  967.       order by name
  968.    return (0)
  969. end
  970.  
  971. /*
  972. **  Verify the database name and get info
  973. */
  974. select @dbid = dbid, @dbsid = sid 
  975.     ,@orig_db_status = status
  976.     ,@orig_db_status2 = status2
  977.    from master.dbo.sysdatabases
  978.       where name = @dbname
  979.  
  980. /*
  981. **  If @dbname not found, say so and list the databases.
  982. */
  983. if @dbid is null
  984.    begin
  985.       raiserror(15010,-1,-1,@dbname)
  986.       print ' '
  987.       select 'Available databases:' = name
  988.          from master.dbo.sysdatabases
  989.       return (1)
  990.    end
  991.  
  992. /*
  993. ** If no option was supplied, display current settings.
  994. */
  995. if @optname is null
  996.    begin
  997.       select 'The following options are set:' = v.name
  998.          from master.dbo.spt_values v, master.dbo.sysdatabases d
  999.             where d.name=@dbname
  1000.                and ((number & @allstatopts <> 0
  1001.                      and number not in (-1,@allstatopts) 
  1002.                      and v.type = 'D'
  1003.                      and (v.number & d.status)=v.number)
  1004.                  or (number & @allcatopts <> 0
  1005.                      and number not in (-1,@allcatopts) 
  1006.                      and v.type = 'DC'
  1007.                      and d.category & v.number <> 0)
  1008.                  or (number & @alloptopts <> 0
  1009.                      and number not in (-1,@alloptopts) 
  1010.                      and v.type = 'D2'
  1011.                      and d.status2 & v.number <> 0))
  1012.       return(0)
  1013.    end
  1014.  
  1015. if lower(@optvalue) not in ('true', 'false', 'on', 'off') and @optvalue is not null
  1016.    begin
  1017.       raiserror(15241,-1,-1)
  1018.       return (1)
  1019.    end
  1020.  
  1021. /*
  1022. **  Use @optname and try to find the right option.
  1023. **  If there isn't just one, print appropriate diagnostics and return.
  1024. */
  1025. select @optcount = count(*) ,@fulloptname = min(name)
  1026.       from master.dbo.spt_values
  1027.       where lower(name) like '%' + lower(@optname) + '%'
  1028.          and ((type = 'D'
  1029.               and number & @allstatopts <> 0
  1030.               and number not in (-1,@allstatopts))
  1031.           or (type = 'DC'
  1032.               and number & @allcatopts <> 0
  1033.               and number not in (-1,@allcatopts))
  1034.             or (type = 'D2'
  1035.               and number & @alloptopts <> 0
  1036.               and number not in (-1,@alloptopts)))
  1037.  
  1038. /*
  1039. **  If no option, show the user what the options are.
  1040. */
  1041. if @optcount = 0
  1042.    begin
  1043.       raiserror(15011,-1,-1,@optname)
  1044.       print ' '
  1045.  
  1046.       select 'Settable database options:' = name
  1047.          from master.dbo.spt_values
  1048.          where (type = 'D'
  1049.                and number & @allstatopts <> 0
  1050.                and number not in (-1,@allstatopts))  /* Eliminate non-option entries */
  1051.             or (type = 'DC'
  1052.                and number & @allcatopts <> 0
  1053.                and number not in (-1,@allcatopts))
  1054.             or (type = 'D2'
  1055.                and number & @alloptopts <> 0
  1056.                and number not in (-1,@alloptopts))
  1057.          order by name
  1058.  
  1059.       return (1)
  1060.    end
  1061.  
  1062.  
  1063. /*
  1064. **  If more than one option like @optname, show the duplicates and return.
  1065. */
  1066. if @optcount > 1
  1067.    begin
  1068.       raiserror(15242,-1,-1,@optname)
  1069.       print ' '
  1070.  
  1071.       select duplicate_options = name
  1072.          from master.dbo.spt_values
  1073.          where lower(name) like '%' + lower(@optname) + '%'
  1074.             and ((type = 'D'
  1075.                  and number & @allstatopts <> 0
  1076.                  and number not in (-1,@allstatopts))
  1077.               or (type = 'DC'
  1078.                  and number & @allcatopts <> 0
  1079.                  and number not in (-1,@allcatopts))
  1080.               or (type = 'D2'
  1081.                  and number & @alloptopts <> 0
  1082.                  and number not in (-1,@alloptopts))
  1083.                 )
  1084.       return (1)
  1085.    end
  1086.  
  1087. /* 
  1088. ** read the status value to be set or the category value to be set
  1089. */
  1090. select @statvalue = number
  1091.       from master.dbo.spt_values
  1092.       where lower(name) = lower(@fulloptname) 
  1093.       and type = 'D'
  1094.  
  1095. select @statvalue2 = number
  1096.       from master.dbo.spt_values
  1097.       where lower(name) = lower(@fulloptname) 
  1098.       and type = 'D2'
  1099.  
  1100. /* 
  1101. ** if a category option is being set, set the status option value to be 0
  1102. ** so that we won't be inserting a null value to sysdatabases.status
  1103. */
  1104. if @statvalue is null
  1105.       select @statvalue = 0
  1106.  
  1107. if @statvalue2 is null
  1108.       select @statvalue2 = 0
  1109.  
  1110. select @catvalue = number
  1111.       from master.dbo.spt_values
  1112.       where lower(name) = lower(@fulloptname) 
  1113.       and type = 'DC'
  1114.  
  1115.     select @opt_autoclose = number from master.dbo.spt_values 
  1116.         where type = 'D' and name = 'autoclose'
  1117.  
  1118.     select @opt_trunclogonchkpt = number from master.dbo.spt_values 
  1119.         where type = 'D' and name = 'trunc. log on chkpt.'
  1120.  
  1121.     select @opt_tornpage = number from master.dbo.spt_values 
  1122.         where type = 'D' and name = 'torn page detection'
  1123.  
  1124.     select @opt_catnull = number from master.dbo.spt_values 
  1125.         where type = 'D2' and name = 'concat null yields null'
  1126.  
  1127.     select @opt_ansinulldefault = number from master.dbo.spt_values 
  1128.         where type = 'D2' and name = 'ANSI null default'
  1129.  
  1130.     select @opt_defaulttolocalcursor = number from master.dbo.spt_values 
  1131.         where type = 'D2' and name = 'default to local cursor'
  1132.  
  1133.     select @opt_selectintobulkcopy = number from master.dbo.spt_values 
  1134.         where type = 'D' and name = 'select into/bulkcopy'
  1135.  
  1136.     select @opt_recursivetriggers = number from master.dbo.spt_values 
  1137.         where type = 'D2' and name = 'recursive triggers'
  1138.  
  1139.     select @opt_offline = number from master.dbo.spt_values 
  1140.         where type = 'D' and name = 'offline'
  1141.  
  1142.     select @opt_quotedid = number from master.dbo.spt_values 
  1143.         where type = 'D2' and name = 'quoted identifier'
  1144.  
  1145.     select @opt_cursorcommitclose = number from master.dbo.spt_values 
  1146.         where type = 'D2' and name = 'cursor close on commit'
  1147.  
  1148.     select @opt_compnull = number from master.dbo.spt_values 
  1149.         where type = 'D2' and name = 'ANSI nulls'
  1150.  
  1151.     select @opt_ansiwarnings = number from master.dbo.spt_values 
  1152.         where type = 'D2' and name = 'ANSI warnings'
  1153.  
  1154.     select @opt_autocrtstats = number from master.dbo.spt_values 
  1155.         where type = 'D2' and name = 'auto create statistics'
  1156.  
  1157.     select @opt_autoupdstats = number from master.dbo.spt_values 
  1158.         where type = 'D2' and name = 'auto update statistics'
  1159.  
  1160. if @statvalue > 0
  1161. begin
  1162.  
  1163. /*
  1164. **  You can not change any of the options in master, except the 'trunc log on
  1165. **  checkpoint' option (8).  If the user tries to do so tell them they can't.
  1166. */
  1167. if (@dbid = db_id('master') and @statvalue <> @opt_trunclogonchkpt and @optvalue is not null)
  1168.    begin
  1169.       raiserror(15243,-1,-1,@optname)
  1170.       return (1)
  1171.    end
  1172.  
  1173. /* Check for allowable options on tempdb */
  1174. if (@dbid = db_id('tempdb')
  1175.     and @optvalue is not null)
  1176.     begin
  1177.         raiserror(15324,-1,-1,@optname, @dbname )
  1178.         return (1)
  1179.     end
  1180.  
  1181. /*Check for allowable option on Model and MSDB*/
  1182. if (@dbid in (db_id('model'), db_id('msdb')) and 
  1183.     @statvalue = @opt_offline
  1184.     and @optvalue is not null)
  1185.     begin
  1186.         raiserror(15324,-1,-1,@optname, @dbname )
  1187.         return (1)
  1188.     end
  1189. end
  1190.  
  1191.  
  1192. if @statvalue2 > 0
  1193. begin
  1194. /* Check for allowable options on tempdb */
  1195. if (@dbid = db_id('tempdb') and not @statvalue2 in 
  1196.     ( @opt_catnull, @opt_recursivetriggers 
  1197.     ,@opt_ansinulldefault,@opt_defaulttolocalcursor
  1198.     ,@opt_quotedid, @opt_cursorcommitclose, @opt_compnull
  1199.   ,@opt_ansiwarnings, @opt_autocrtstats, @opt_autoupdstats) 
  1200.     and @optvalue is not null)
  1201.     begin
  1202.         raiserror(15324,-1,-1,@optname, @dbname )
  1203.         return (1)
  1204.     end
  1205. end
  1206.  
  1207. /*
  1208. **  Only the SA or the dbo of @dbname can execute the update part
  1209. **  of this procedure so check.
  1210. */
  1211. if (not (is_srvrolemember('sysadmin') = 1))
  1212.     and suser_sid() <> @dbsid and @optvalue is not null
  1213.     -- ALSO ALLOW db_owner ONLY IF DB REQUESTED IS CURRENT DB
  1214.     and (@dbid <> db_id() or is_member('db_owner') <> 1)
  1215.    begin
  1216.       raiserror(15244,-1,-1)
  1217.       return (1)
  1218.    end
  1219.  
  1220. /*
  1221. **  If we're in a transaction, disallow this since it might make recovery
  1222. **  impossible.
  1223. */
  1224. set implicit_transactions off
  1225. if @@trancount > 0 and @optvalue is not null
  1226.    begin
  1227.       raiserror(15002,-1,-1,'sp_dboption')
  1228.       return (1)
  1229.    end
  1230.  
  1231.  
  1232. /*
  1233. **  Just want to see current setting of specified option.
  1234. */
  1235. if @optvalue is null
  1236. begin
  1237.       select OptionName = v.name
  1238.  
  1239.             ,CurrentSetting =
  1240.                CASE
  1241.                   When ( ((v.number & d.status) = v.number
  1242.                           and v.type = 'D')
  1243.                       or (d.category & v.number <> 0
  1244.                            and v.type = 'DC')
  1245.                       or (d.status2 & v.number <> 0
  1246.                            and v.type = 'D2')
  1247.                        )
  1248.                      Then 'ON'
  1249.                   When NOT
  1250.                        ( ((v.number & d.status) = v.number
  1251.                           and v.type = 'D')
  1252.                       or (d.category & v.number <> 0
  1253.                            and v.type = 'DC')
  1254.                       or (d.status2 & v.number <> 0
  1255.                            and v.type = 'D2')
  1256.                        )
  1257.                      Then 'off'
  1258.                END
  1259.  
  1260.          from master.dbo.spt_values v, master.dbo.sysdatabases d
  1261.             where d.name=@dbname
  1262.                and ((v.number & @allstatopts <> 0
  1263.                      and v.number not in (-1,@allstatopts)   /* Eliminate non-option entries */
  1264.                      and v.type = 'D')
  1265.                  or (v.number & @allcatopts <> 0
  1266.                      and v.number not in (-1,@allcatopts)   /* Eliminate non-option entries */
  1267.                      and v.type = 'DC')
  1268.                  or (v.number & @alloptopts <> 0
  1269.                      and v.number not in (-1,@alloptopts)   /* Eliminate non-option entries */
  1270.                      and v.type = 'D2')
  1271.                    )
  1272.                 and lower(v.name) = lower(@fulloptname)
  1273.  
  1274.    return (0)
  1275. end
  1276.  
  1277.  
  1278. ---- Pre-detect 'single user' conflicts.
  1279. select @opt_bit_singleuser = number from master.dbo.spt_values
  1280.   where type='D  ' and name='single user'
  1281. if (@fulloptname           ='single user') --13834
  1282.    begin
  1283.    select @int1 = count(*) from master.dbo.sysprocesses
  1284.       where dbid = @dbid and spid<>@@spid
  1285.    if (@int1 > 0 and
  1286.     (@orig_db_status & @opt_bit_singleuser > 0 or
  1287.      lower(@optvalue) in ('true', 'on'))
  1288.       )
  1289.       begin
  1290.       raiserror(15089,-1,-1,@fulloptname)
  1291.       return (1)
  1292.       end
  1293.    end
  1294.  
  1295. /*
  1296. **  Now update sysdatabases.
  1297. */
  1298. if lower(@optvalue) in ('true','on')
  1299. begin
  1300.    /*
  1301.    **  If this is the option to make the database offline
  1302.    **  we need to do some checking first to make sure no users.
  1303.    **  Unless it's the master db, no one can be using it.
  1304.    **  If it's the master db, only the SA may be using it.
  1305.    */
  1306.    if @statvalue in (512)
  1307.       and (select count(*) from master.dbo.sysprocesses
  1308.          where dbid = @dbid
  1309.          and sid <> 0x1) > 0
  1310.       begin
  1311.          raiserror(15069,-1,-1)
  1312.          return (1)
  1313.       end
  1314.  
  1315.    /*
  1316.    ** If we're setting the database 'offline' - use 'dbcc dbcontrol'
  1317.    ** rather than setting the status bit directly.
  1318.    */
  1319.    if @statvalue = 512  -- 512 ON means db is Offline.
  1320.    begin
  1321.  
  1322.       if (0 = (@statvalue & (select status from master.dbo.sysdatabases where name=@dbname)))
  1323.          begin  -- Currently db is Online.
  1324.  
  1325.          dbcc dbcontrol(@dbname,offline)
  1326.          if @@error>0
  1327.             begin
  1328.                raiserror(15245,-1,-1)
  1329.                return (1)
  1330.             end
  1331.          else
  1332.             raiserror(15327,-1,-1)
  1333.          end
  1334.       else
  1335.          raiserror(15328,-1,-1)
  1336.  
  1337.       /*
  1338.       ** Don't need to continue and set status bit or 'checkpoint'
  1339.       ** the database if option was 'offline' since the dbcc
  1340.       ** command does.
  1341.       */
  1342.       return(0)   /* Don't need to continue and 'checkpoint' db for this
  1343.             ** option. */
  1344.    end
  1345.  
  1346.    /* 
  1347.    ** If we're setting the database  'read only', - use dbcc dbcontrol' 
  1348.    ** rather than setting the status bit directly
  1349.    */
  1350.    if @statvalue = 1024 -- 1024 ON means db is Read only
  1351.    begin
  1352.       if (0 = (@statvalue & (select status from master.dbo.sysdatabases where name = @dbname)))
  1353.          begin  -- currently db is not readonly
  1354.          
  1355.          dbcc dbcontrol(@dbname, readonly)
  1356.          if @@error>0
  1357.             begin
  1358.                raiserror(15612, -1, -1)
  1359.                return (1)
  1360.             end
  1361.          else
  1362.             raiserror(15613, -1, -1)
  1363.          end
  1364.      else
  1365.          raiserror(15614, -1, -1)
  1366.     
  1367.      /* 
  1368.      ** We are done with the readony option
  1369.      */    
  1370.      return (0)
  1371.    
  1372.    end 
  1373.  
  1374.    /* 
  1375.    ** If we're setting the database 'single user', - use dbcc dbcontrol' 
  1376.    ** rather than setting the status bit directly
  1377.    */
  1378.    if @statvalue = 4096 -- 4096 ON means db is single user
  1379.    begin
  1380.       if (0 = (@statvalue & (select status from master.dbo.sysdatabases where name = @dbname)))
  1381.          begin  -- currently db is not singleuser
  1382.          
  1383.          dbcc dbcontrol(@dbname, single)
  1384.          if @@error>0
  1385.             begin
  1386.                raiserror(15615, -1, -1)
  1387.                return (1)
  1388.             end
  1389.          else
  1390.             raiserror(15616, -1, -1)
  1391.          end
  1392.      else
  1393.          raiserror(15617, -1, -1)
  1394.     
  1395.      /* 
  1396.      ** We are done with the readony option
  1397.      */    
  1398.      return (0)
  1399.    
  1400.    end 
  1401.  
  1402.    if @catvalue = 1   /* We're publishing the database. */
  1403.       begin
  1404.          select @exec_stmt = quotename(@dbname, '[')   + '.dbo.sp_replicationdboption'
  1405.           /* @dbname = N' +   quotename(@dbname, '''')  + ', @optname = ''publish'' , @value =  ''true'''*/
  1406.  
  1407.           exec @returncode = @exec_stmt @dbname,'publish','true'
  1408.  
  1409.         if @returncode = 0
  1410.         begin
  1411.             raiserror(15435,-1,-1)
  1412.             return(0)
  1413.         end
  1414.         else
  1415.             return (1)   
  1416.       end
  1417.  
  1418.    if @catvalue = 2  /* Allowing subscriptions in the database. */
  1419.       begin
  1420.            update master.dbo.sysdatabases set category = category | 2
  1421.             where name = @dbname
  1422.          raiserror(15436,-1,-1)
  1423.          return (0)
  1424.       end
  1425.  
  1426.     if @catvalue = 4    /* Allowing merge publishing in the database. */
  1427.         begin
  1428.             select @exec_stmt = quotename(@dbname, '[')   + '.dbo.sp_replicationdboption'
  1429.             /*@dbname = N' +   quotename(@dbname, '''')  + ', @optname = ''merge publish'' , @value =  ''true'''*/
  1430.             exec @returncode = @exec_stmt @dbname,'merge publish','true'
  1431.  
  1432.             if @returncode = 0
  1433.             begin
  1434.                 raiserror(15437,-1,-1)
  1435.                 return(0)
  1436.             end
  1437.             else
  1438.                 return (1)
  1439.         end
  1440.  
  1441.    /* All other options get handled identically. */
  1442.    update master.dbo.sysdatabases 
  1443.         set status = status | @statvalue,
  1444.         status2 = status2 | @statvalue2
  1445.       where dbid = @dbid
  1446. end
  1447.  
  1448. /*
  1449. **  We want to set the requested option off.
  1450. */
  1451.  
  1452. else
  1453.  
  1454. begin
  1455.    if @statvalue = 1024
  1456.         and (0 <> (2097152 & (select status from master.dbo.sysdatabases where dbid=@dbid)))
  1457.    begin
  1458.         /* The db is in standby mode (2097152 = 0x200000 = DBT_STANDBY)
  1459.            so disallow turning the read-only bit off */
  1460.         raiserror(15030,-1,-1)
  1461.         return (1)
  1462.    end
  1463.  
  1464.    if @statvalue = 512     /* We're bringing it online. */
  1465.    begin
  1466.         if (0 = (@statvalue & (select status from master.dbo.sysdatabases where name=@dbname)))
  1467.          -- Currently db is Online.
  1468.             raiserror(15438,-1,-1)
  1469.         else
  1470.         begin
  1471.             dbcc dbcontrol(@dbname,online)
  1472.             if @@error>0
  1473.             begin
  1474.                 return (1)
  1475.             end
  1476.             else
  1477.             raiserror(15439,-1,-1)
  1478.         end
  1479.  
  1480.         return(0)
  1481.     end
  1482.  
  1483.    if @statvalue = 1024     /* We're turning off readonly. */
  1484.    begin
  1485.         if (0 = (@statvalue & (select status from master.dbo.sysdatabases where name=@dbname)))
  1486.          -- Currently db is not readonly.
  1487.             raiserror(15619,-1,-1)
  1488.         else
  1489.         begin
  1490.             dbcc dbcontrol(@dbname,readwrite)
  1491.             if @@error>0
  1492.             begin
  1493.                 return (1)
  1494.             end
  1495.             else
  1496.             raiserror(15618,-1,-1)
  1497.         end
  1498.  
  1499.         return(0)
  1500.     end
  1501.  
  1502.    if @statvalue = 4096     /* We're turning off singleuser. */
  1503.    begin
  1504.         if (0 = (@statvalue & (select status from master.dbo.sysdatabases where name=@dbname)))
  1505.          -- Currently db is not singleuser.
  1506.             raiserror(15621,-1,-1)
  1507.         else
  1508.         begin
  1509.             dbcc dbcontrol(@dbname,multi)
  1510.             if @@error>0
  1511.             begin
  1512.                 return (1)
  1513.             end
  1514.             else
  1515.             raiserror(15620,-1,-1)
  1516.         end
  1517.  
  1518.         return(0)
  1519.     end
  1520.  
  1521.     if @catvalue = 1   /* We're disabling publishing for the database. */
  1522.     begin
  1523.         select @exec_stmt = quotename(@dbname, '[')   + '.dbo.sp_replicationdboption'
  1524.         /* @dbname = N' +   quotename(@dbname, '''')  + ', @optname = ''publish'' , @value =  ''false'''*/
  1525.  
  1526.         exec @returncode = @exec_stmt @dbname, 'publish', 'true'
  1527.  
  1528.         if @returncode = 0
  1529.         begin
  1530.             raiserror(15440,-1,-1)
  1531.             return(0)
  1532.         end
  1533.         else
  1534.             return (1)
  1535.  
  1536.     end
  1537.  
  1538.     if @catvalue = 2  /* We're disabling subscriptions to database. */
  1539.     begin
  1540.         update master.dbo.sysdatabases set category = category & ~2
  1541.         where name = @dbname
  1542.          raiserror(15441,-1,-1)
  1543.         return (0)
  1544.     end
  1545.  
  1546.     if @catvalue = 4    /* Disable merge publishing in the database. */
  1547.         begin
  1548.          select @exec_stmt = quotename(@dbname, '[')   + '.dbo.sp_replicationdboption'
  1549.          /*@dbname = N' +   quotename(@dbname, '''')  + ', @optname = ''merge publish'' , @value =  ''false'''*/
  1550.          exec @returncode = @exec_stmt @dbname, 'merge publish', 'false'
  1551.  
  1552.         if @returncode = 0
  1553.         begin
  1554.             raiserror(15442,-1,-1)
  1555.             return(0)
  1556.         end
  1557.         else
  1558.             return (1)
  1559.         end
  1560.  
  1561.         /* All other options get handled identically. */
  1562.     update master.dbo.sysdatabases 
  1563.         set status = status & ~@statvalue
  1564.         ,status2 = status2 & ~@statvalue2
  1565.         where dbid = @dbid
  1566. end
  1567.  
  1568. /*
  1569. **  CHECKPOINT the database that was changed.
  1570. */
  1571. raiserror(15443,-1,-1)
  1572.  
  1573. select @exec_stmt = 'use ' +  quotename(@dbname, '[')   + ' checkpoint'         
  1574. exec (@exec_stmt)        
  1575. select @int1 = @@error
  1576. if (@int1 <> 0)
  1577.     begin
  1578.     update         master.dbo.sysdatabases
  1579.         set     status = @orig_db_status
  1580.              ,status2 = @orig_db_status2
  1581.         where     dbid   = @dbid
  1582.     end
  1583. else
  1584.     /* 
  1585.     **flush the stored procedures in the database involved for recompile
  1586.     ** if changing compile time options 
  1587.     */
  1588.     begin
  1589.         dbcc flushprocindb(@dbid)
  1590.     end
  1591.  
  1592.  
  1593. return (0) -- sp_dboption
  1594. go
  1595. set ansi_nulls off
  1596. go
  1597. /*ANSI_NULLS OFF  for after creation of sp_dboption*/
  1598.  
  1599. checkpoint
  1600. go
  1601.  
  1602. raiserror(15339,-1,-1,'sp_dbcmptlevel')
  1603. go
  1604. /*ANSI_NULLS ON  for creation of sp_dbcmptlevel*/
  1605. set ansi_nulls on
  1606. go
  1607. create procedure sp_dbcmptlevel  -- 1997/04/15
  1608. @dbname sysname = NULL,        /* database name to change */
  1609. @new_cmptlevel tinyint = NULL OUTPUT    /* the new compatibility level to change to */
  1610. as
  1611.  
  1612. set nocount    on
  1613.  
  1614. declare @exec_stmt nvarchar(275)
  1615. declare @returncode    int
  1616. declare @comptlevel    float(8)
  1617. declare @dbid int                /* dbid of the database */
  1618. declare @dbsid varbinary(85)    /* id of the owner of the database */
  1619. declare @orig_cmptlevel tinyint    /* original compatibility level */        
  1620. declare @input_cmptlevel tinyint    /* compatibility level passed in by user */        
  1621.     ,@cmptlvl60 tinyint            /* compatibility to SQL Server Version 6.0 */
  1622.     ,@cmptlvl65 tinyint            /* compatibility to SQL Server Version 6.5 */
  1623.     ,@cmptlvl70 tinyint            /* compatibility to SQL Server Version 7.0 */
  1624. select  @cmptlvl60 = 60,
  1625.         @cmptlvl65 = 65,
  1626.         @cmptlvl70 = 70
  1627.  
  1628.  
  1629. -- SP MUST BE CALLED AT ADHOC LEVEL --
  1630. if (@@nestlevel > 1)
  1631. begin
  1632.     raiserror(15432,-1,-1,'sp_dbcmptlevel')
  1633.     return (1)
  1634. end
  1635.  
  1636. /*
  1637. **  If no @dbname given, just list the valid compatibility level values.
  1638. */
  1639.  
  1640. if @dbname is null
  1641. begin
  1642.    raiserror (15048, -1, -1, @cmptlvl60, @cmptlvl65, @cmptlvl70)
  1643.    return (0)
  1644. end
  1645.  
  1646. /*
  1647. **  Verify the database name and get info
  1648. */
  1649. select @dbid = dbid, @dbsid = sid ,@orig_cmptlevel = cmptlevel
  1650.    from master.dbo.sysdatabases
  1651.       where name = @dbname
  1652.  
  1653. /*
  1654. **  If @dbname not found, say so and list the databases.
  1655. */
  1656. if @dbid is null
  1657.    begin
  1658.       raiserror(15010,-1,-1,@dbname)
  1659.       print ' '
  1660.       select 'Available databases:' = name
  1661.          from master.dbo.sysdatabases
  1662.       return (1)
  1663.    end
  1664.  
  1665. /*
  1666. ** Now save the input compatibility level and initialize the return clevel
  1667. ** to be the current clevel
  1668. */
  1669. select @input_cmptlevel = @new_cmptlevel
  1670. select @new_cmptlevel = @orig_cmptlevel
  1671.  
  1672. /*
  1673. ** If no clevel was supplied, display and output current level.
  1674. */
  1675. if @input_cmptlevel is null
  1676.    begin
  1677.       raiserror(15054, -1, -1, @orig_cmptlevel)
  1678.       return(0)
  1679.    end
  1680.  
  1681. /*
  1682. ** We should not allow the user to change the compatibility level of the master database
  1683. */
  1684. if @dbid = db_id('master')
  1685.     begin
  1686.        raiserror(15417, -1, -1, @dbname)
  1687.        return (1)
  1688.     end
  1689.  
  1690. /*
  1691. ** If invalid clevel given, print usage and return error code
  1692. ** 'usage: sp_dbcmptlevel [dbname [, compatibilitylevel]]'
  1693. */
  1694. if @input_cmptlevel not in (@cmptlvl60, @cmptlvl65, @cmptlvl70)
  1695.    begin
  1696.       raiserror(15416, -1, -1)
  1697.       print ' '
  1698.       raiserror (15048,
  1699.          -1, -1, @cmptlvl60, @cmptlvl65, @cmptlvl70)
  1700.       return (1)
  1701.    end
  1702.  
  1703.  
  1704. /*
  1705. **  Only the SA or the dbo of @dbname can execute the update part
  1706. **  of this procedure so check.
  1707. */
  1708. if (not (is_srvrolemember('sysadmin') = 1)) and suser_sid() <> @dbsid
  1709.     -- ALSO ALLOW db_owner ONLY IF DB REQUESTED IS CURRENT DB
  1710.     and (@dbid <> db_id() or is_member('db_owner') <> 1)
  1711.    begin
  1712.       raiserror(15418,-1,-1)
  1713.       return (1)
  1714.    end
  1715.  
  1716. /*
  1717. ** We should not allow the user to change the compatibility level for 
  1718. ** replicated or distributed databases
  1719. */
  1720. select @comptlevel =    case @input_cmptlevel 
  1721.                             when 60 then 6.0
  1722.                             when 65 then 6.5
  1723.                             when 70 then 7.0
  1724.                         end
  1725.  
  1726. exec @returncode = sp_MSreplicationcompatlevel @dbname, @comptlevel
  1727.  
  1728. if @returncode <> 0
  1729.     begin
  1730.         raiserror(15306, -1, -1)
  1731.         return (1)
  1732.     end
  1733.  
  1734. /*
  1735. **  If we're in a transaction, disallow this since it might make recovery
  1736. **  impossible.
  1737. */
  1738. set implicit_transactions off
  1739. if @@trancount > 0
  1740.    begin
  1741.       raiserror(15002,-1,-1,'sp_dbcmptlevel')
  1742.       return (1)
  1743.    end
  1744.  
  1745.  
  1746. update master.dbo.sysdatabases set cmptlevel = @input_cmptlevel
  1747.       where dbid = @dbid
  1748.  
  1749. /*
  1750. **  CHECKPOINT the database that was changed.
  1751. */
  1752.  
  1753. select @exec_stmt = 'use ' +  quotename(@dbname, '[')   + ' checkpoint'
  1754. exec(@exec_stmt )
  1755. /*
  1756. ** If checkpoint unsuccessful, restore the old compatibility level,
  1757. ** otherwise update output clevel and flush all the SPs of this database
  1758. ** from the cache
  1759. */
  1760. if (@@error <> 0)
  1761.     begin
  1762.     update         master.dbo.sysdatabases
  1763.         set     cmptlevel = @orig_cmptlevel
  1764.         where     dbid   = @dbid
  1765.     end
  1766. else
  1767.     begin
  1768.     dbcc flushprocindb(@dbid)
  1769.     select @new_cmptlevel = @input_cmptlevel
  1770.     end
  1771.  
  1772. return (0) -- sp_dbcmptlevel
  1773. go
  1774. set ansi_nulls off
  1775. go
  1776. /*ANSI_NULLS OFF  for after creation of sp_dbcmptlevel*/
  1777.  
  1778. ---- Fallback 6.5 sprocs removed for 7.0 until re-coded from scratch to match new tables.
  1779. /************************  BEGIN-FALLBACK-STORED-PROCS ***********************/
  1780. raiserror(15339,-1,-1,'sp_fallback_MS_sel_fb_svr')
  1781. go
  1782.  
  1783. create procedure sp_fallback_MS_sel_fb_svr  --- 1997/05/30 02:44
  1784.     @pFallbackSvrName    character varying(30)   OUTPUT
  1785. as
  1786. /********1*********2*********3*********4*********5*********6*********7**
  1787.  
  1788.       This sproc is used by ODBC & DBLib when first connecting.
  1789.       This sproc will assign a null to the output parm.
  1790.       Note: This will need to be changed to return the name
  1791.             of the virtual server once WolfPack support is enabled.
  1792. *********1*********2*********3*********4*********5*********6*********7*/
  1793.  
  1794. Set nocount                   on
  1795. Set ansi_nulls                on
  1796.  
  1797. SELECT       @pFallbackSvrName   = null
  1798.  
  1799. Return 0
  1800. go
  1801.  
  1802. grant execute on sp_fallback_MS_sel_fb_svr to public
  1803. go
  1804.  
  1805. checkpoint
  1806. go
  1807. /*************************  END-FALLBACK-STORED-PROCS ************************/
  1808.  
  1809. raiserror(15339,-1,-1,'sp_validname')
  1810. go
  1811. CREATE PROCEDURE sp_validname
  1812.     @name            sysname,
  1813.     @raise_error    bit = 1
  1814. AS
  1815.     -----------------------------------------------------
  1816.     --    This SP checks for valid SQL-Server identifiers.
  1817.     --    For 7.0+, these are the very-simple checks below.
  1818.     --    All non-binary-zero (UNICODE) characters we just
  1819.     --    accept as being valid.
  1820.     -----------------------------------------------------
  1821.     declare @index    int
  1822.  
  1823.     Set nocount on
  1824.  
  1825.     -- Name cannot be NULL or empty ("")
  1826.     -- Blank identifiers (" ") are allowed
  1827.     IF (@name is null OR datalength(@name) = 0)
  1828.     begin
  1829.         if @raise_error = 1
  1830.             raiserror (15004,-1,-1)
  1831.         return (1)
  1832.     end
  1833.  
  1834.     -- Name cannot contain a binary-zero character
  1835.     select @index = charindex(convert(nchar(1),0x00), @name)
  1836.     while (@index <> 0)
  1837.     begin
  1838.         if unicode(substring(@name, @index, 1)) = 0
  1839.         begin
  1840.             if @raise_error = 1
  1841.                 raiserror(15006,-1,-1,@name)
  1842.             return (1)
  1843.         end
  1844.         if @index >= len(@name)
  1845.             select @index = 0
  1846.         else
  1847.         begin
  1848.             select @name = substring(@name, @index+1, len(@name)-@index)
  1849.             select @index = charindex(convert(nchar(1),0x00), @name)
  1850.         end
  1851.     end
  1852.  
  1853.     -- TH-TH-TH-THAT'S IT!
  1854.     return (0) -- sp_validname
  1855. go
  1856.  
  1857.  
  1858. raiserror(15339,-1,-1,'sp_validlang')
  1859. go
  1860. create procedure sp_validlang --- 1996/04/08 00:00
  1861. @name    sysname
  1862. as
  1863.  
  1864. /* Check to see if this language is in Syslanguages. */
  1865. if exists (select * from master.dbo.syslanguages where name = @name or alias = @name)
  1866.     or @name = N'us_english' 
  1867.     return(0)
  1868.  
  1869. raiserror(15033,-1,-1,@name)
  1870. return (1) -- sp_validlang
  1871. go
  1872.  
  1873. checkpoint
  1874. go
  1875.  
  1876. raiserror(15339,-1,-1,'sp_addmessage')
  1877. go
  1878. create procedure sp_addmessage --- 1996/04/08 00:00
  1879. @msgnum int = null,        -- Number of new message.
  1880. @severity smallint = null,    -- Severity of new message.
  1881. @msgtext nvarchar(255) = null,    -- Text of new message.
  1882. @lang sysname = null,       -- language (name) of new message
  1883. @with_log varchar(5) = 'FALSE', -- Whether the message will ALWAYS go to the NT event log
  1884. @replace varchar(7) = null    -- Optional parameter to specify that
  1885.                 -- existing message with same number
  1886.                 -- should be overwritten.
  1887. as
  1888. declare @retcode int
  1889. declare @langid smallint
  1890. declare @msglangid smallint
  1891. declare @dlevel smallint
  1892.  
  1893. if @msgnum is null or @severity is null or @msgtext is null
  1894.     begin
  1895.         raiserror(15071,-1,-1)
  1896.         return(1)
  1897.     end
  1898.  
  1899. /*
  1900. ** User defined messages must be > 50000.
  1901. */
  1902. if @msgnum <= 50000
  1903.     begin
  1904.         raiserror(15040,-1,-1)
  1905.         return(1)
  1906.     end
  1907.  
  1908. /*
  1909. ** Valid severity range for user defined messges is 1 to 25.
  1910. */
  1911. if @severity not between 1 and 25
  1912.     begin
  1913.         raiserror(15041,-1,-1)
  1914.         return(1)
  1915.     end
  1916.  
  1917. /*
  1918. ** Only the SA may add messages with severity > 18 or which set the WITH_LOG option to 'true'
  1919. */
  1920. if (not (is_srvrolemember('sysadmin') = 1)) and ((@severity > 18) or (rtrim(upper(@with_log)) = 'TRUE'))
  1921.     begin
  1922.         raiserror(15042,-1,-1)
  1923.         return (1)
  1924.     end
  1925.  
  1926. /*
  1927. ** Verify the language
  1928. */
  1929. if @lang is not null
  1930.     begin        
  1931.         exec @retcode = sp_validlang @lang
  1932.         if @retcode <>  0
  1933.             return(1)
  1934.     end
  1935. else
  1936.     select @lang = @@language
  1937.  
  1938. /*
  1939. ** Get langid from syslanguages; us_english won't exist, so use 0.
  1940. */
  1941. select @langid = langid, @msglangid = msglangid
  1942.     from master.dbo.syslanguages where name = @lang or alias = @lang
  1943.  
  1944. select @langid = isnull(@langid, 0)
  1945. select @msglangid = isnull(@msglangid, 1033)
  1946.  
  1947. /*
  1948. ** @with_log must be 'TRUE' or 'FALSE'
  1949. */
  1950. if (upper(@with_log) not in ('TRUE', 'FALSE'))
  1951.     begin
  1952.         raiserror(15271,-1,-1)
  1953.         return (1)
  1954.     end
  1955.  
  1956. /*
  1957. ** Set the dlevel bit accordingly
  1958. */
  1959. if (rtrim(upper(@with_log)) = 'TRUE')
  1960.         select @dlevel = 0x80
  1961. else
  1962.         select @dlevel = 0x0
  1963.  
  1964. /*
  1965. ** If we're adding a non-us_english message, make sure the us_english version already exists.
  1966. */
  1967. if (@langid <> 0) and not exists (select * from master.dbo.sysmessages where error=@msgnum and msglangid = 1033)
  1968.     begin
  1969.         raiserror(15279,-1,-1,@lang)
  1970.         return(1)
  1971.     end
  1972.  
  1973. /*
  1974. ** If we're adding a non-us_english message, make sure that the severity matches that of the us_english version
  1975. */
  1976. if (@langid <> 0 ) and not exists (select * from master.dbo.sysmessages where error=@msgnum and severity=@severity and msglangid = 1033)
  1977.     begin
  1978.         declare @us_english_severity smallint
  1979.         select @us_english_severity = severity from master.dbo.sysmessages where error=@msgnum and msglangid = 1033
  1980.         raiserror(15304,-1,-1,@lang,@us_english_severity)
  1981.         return(1)
  1982.     end
  1983.  
  1984. /*
  1985. **  Does this message already exist, and if so are we REPLACEing it?
  1986. */
  1987. if (select count(*) from master.dbo.sysmessages where error=@msgnum and msglangid=@msglangid) > 0
  1988.     if lower(@replace) = 'replace'
  1989.         begin
  1990.             raiserror(15342,-1,-1)
  1991.             delete from master.dbo.sysmessages where error = @msgnum and msglangid = @msglangid
  1992.             /*
  1993.             ** If we're REPLACEing a us_english message, make sure any non-us_english messages get updated with the same severity
  1994.             */
  1995.             if (@langid = 0)
  1996.                 begin
  1997.                     update master.dbo.sysmessages set severity = @severity
  1998.                     where error = @msgnum and msglangid <> 1033
  1999.                 end
  2000.         end
  2001.     else
  2002.         begin
  2003.             /*
  2004.             ** The 'replace' option wasn't specified and a
  2005.             ** msg. with the number already exists.
  2006.             */
  2007.             raiserror(15043,-1,-1)
  2008.             return(1)
  2009.         end
  2010.  
  2011. /*
  2012. **  Create the message.
  2013. */
  2014. insert into master.dbo.sysmessages(error,severity,description,dlevel,msglangid)
  2015.     values (@msgnum,@severity,@msgtext,@dlevel,@msglangid)
  2016.  
  2017. if (@@error = 0)
  2018.    raiserror(15343,-1,-1)
  2019.  
  2020. return (0) -- sp_addmessage
  2021. go
  2022.  
  2023.  
  2024.  
  2025. raiserror(15339,-1,-1,'sp_addumpdevice')
  2026. go
  2027. create procedure sp_addumpdevice -- 1995/09/07 12:01
  2028. @devtype varchar(20),      /* disk, tape, or diskette */
  2029. @logicalname   sysname,      /* logical name of the device */
  2030. @physicalname  nvarchar(260),     /* physical name of the device */
  2031. @cntrltype  smallint = null,  /* controller type - ignored. */
  2032. @devstatus  varchar(40) = 'noskip'  /* device characteristics */
  2033. as
  2034.  
  2035. declare @status smallint      /* status bits for device */
  2036. declare @returncode int
  2037.  
  2038. /*
  2039. **  An open txn might jeopardize a recovery.
  2040. */
  2041. set implicit_transactions off
  2042. if @@trancount > 0
  2043.    begin
  2044.       raiserror(15002,-1,-1,'sp_addumpdevice')
  2045.       return (1)
  2046.    end
  2047.  
  2048. /*
  2049. **  You must be SA to execute this sproc.
  2050. */
  2051. if (not is_srvrolemember('diskadmin') = 1)
  2052.    begin
  2053.       raiserror(15003,-1,-1, 'diskadmin')
  2054.       return (1)
  2055.    end
  2056.  
  2057. select @devtype=lower(@devtype)
  2058.  
  2059. /*
  2060. **  Check out the @devtype.
  2061. */
  2062. if @devtype not in ('disk', 'tape', 'diskette', 'pipe', 'virtual_device')
  2063.    begin
  2064.       raiserror(15044,-1,-1,@devtype)
  2065.       return (1)
  2066.    end
  2067.  
  2068. /*
  2069. **  Check the args are not NULL.
  2070. */
  2071. if @logicalname is null
  2072.    begin
  2073.       raiserror(15045,-1,-1)
  2074.       return(1)
  2075.    end
  2076.  
  2077. /*
  2078. **  Check to see that the @logicalname is valid.
  2079. */
  2080. exec @returncode = sp_validname @logicalname
  2081. if @returncode <> 0
  2082.    return(1)
  2083.  
  2084. if @physicalname is null
  2085.    begin
  2086.       raiserror(15046,-1,-1)
  2087.       return(1)
  2088.    end
  2089.  
  2090. /*
  2091. **  Make sure physical file name would be unique among devices.
  2092. */
  2093. if exists (select * from master.dbo.sysdevices where phyname = @physicalname)
  2094.    begin
  2095.       raiserror(15061,-1,-1,@physicalname)
  2096.       return (1)
  2097.    end
  2098.  
  2099. /*
  2100. **  Prohibit certain special english words from being logical names.
  2101. */
  2102. if (@logicalname IN ('disk' ,'diskette' ,'tape' ,'floppy'))
  2103.    begin
  2104.       raiserror(15285,-1,-1,@logicalname)
  2105.       return (1)
  2106.    end
  2107.  
  2108. /*
  2109. **  Make sure that a device with @logicalname doesn't already exist.
  2110. */
  2111. if exists (select * from master.dbo.sysdevices where name = @logicalname)
  2112.    begin
  2113.       raiserror(15026,-1,-1,@logicalname)
  2114.       return (1)
  2115.    end
  2116.  
  2117. /*
  2118. **  Always turn on the dump status bit.
  2119. */
  2120. select @status = 16
  2121.  
  2122. /*
  2123. **  If @devtype is a tape then check to see if devstatus is 'skip'.
  2124. */
  2125. if @devtype = 'tape'
  2126.    begin
  2127.       if @devstatus not in ('noskip','skip')
  2128.          begin
  2129.             raiserror(15047,-1,-1)
  2130.             return (1)
  2131.          end
  2132.  
  2133.       if @devstatus = 'skip' select @status = @status | 8
  2134.    end
  2135.  
  2136. /*
  2137. **  If a disk then the cntrltype = 2
  2138. */
  2139. if @devtype = 'disk'
  2140.    begin
  2141.       insert into master.dbo.sysdevices
  2142.          (low, high, size, status, cntrltype, name, phyname)
  2143.          values
  2144.          (0, 0, 0, @status, 2, @logicalname, @physicalname)
  2145.       raiserror(15444,-1,-1)
  2146.    end
  2147.  
  2148. /*
  2149. **  If a diskette then the cntrltype in (3,4)
  2150. */
  2151. if @devtype = 'diskette'
  2152.    begin
  2153.       insert into master.dbo.sysdevices
  2154.          (low, high, size, status, cntrltype, name, phyname)
  2155.          values
  2156.          (0, 0, 0, @status, 3, @logicalname, @physicalname)
  2157.       raiserror(15445,-1,-1)
  2158.    end
  2159.  
  2160. /*
  2161. **  Tape device.
  2162. */
  2163. if @devtype = 'tape'
  2164.    begin
  2165.       insert into master.dbo.sysdevices
  2166.          (low, high, size, status, cntrltype, name, phyname)
  2167.          values
  2168.          (0, 0, 0, @status, 5, @logicalname,@physicalname)
  2169.       raiserror(15446,-1,-1)
  2170.    end
  2171.  
  2172. /*
  2173. ** Pipe.
  2174. */
  2175. if @devtype = 'pipe'
  2176.    begin
  2177.       insert into master.dbo.sysdevices
  2178.          (low, high, size, status, cntrltype, name, phyname)
  2179.          values
  2180.          (0, 0, 0, @status, 6, @logicalname,@physicalname)
  2181.       raiserror(15447,-1,-1)
  2182.    end
  2183.  
  2184. /*
  2185. ** Virtual device.
  2186. */
  2187. if @devtype = 'virtual_device'
  2188.    begin
  2189.       insert into master.dbo.sysdevices
  2190.          (low, high, size, status, cntrltype, name, phyname)
  2191.          values
  2192.          (0, 0, 0, @status, 7, @logicalname,@physicalname)
  2193.       raiserror(15031,-1,-1)
  2194.    end
  2195.  
  2196.  
  2197. return (0) -- sp_addumpdevice
  2198. go
  2199.  
  2200.  
  2201.  
  2202. raiserror(15339,-1,-1,'sp_addremotelogin')
  2203. go
  2204. create procedure sp_addremotelogin --- 1996/04/08 00:00
  2205.     @remoteserver    sysname,        /* name of remote server */
  2206.     @loginame       sysname = NULL,        /* user's remote name */
  2207.     @remotename     sysname = NULL        /* user's local user name */
  2208. as
  2209.     declare @srvid smallint
  2210.     declare @sid varbinary(85)
  2211.  
  2212.     -- DISALLOW USER XACT --
  2213.     set implicit_transactions off
  2214.     if @@trancount > 0
  2215.     begin
  2216.         raiserror(15002,-1,-1,'sp_addremotelogin')
  2217.         return (1)
  2218.     end
  2219.  
  2220.     -- CHECK PERMISSIONS
  2221.     if not (is_srvrolemember('securityadmin') = 1)
  2222.     begin
  2223.         raiserror(15232,-1,-1)
  2224.         return (1)
  2225.     end
  2226.  
  2227.     -- VALIDATE SERVER NAME --
  2228.     select @srvid = srvid from master.dbo.sysservers where srvname = @remoteserver
  2229.     if @srvid is null
  2230.     begin
  2231.         raiserror(15015,-1,-1,@remoteserver)
  2232.         return (1)
  2233.     end
  2234.  
  2235.     -- CHECK FOR INVALID PARAMETER SYNTAX --
  2236.     if @loginame is null and @remotename is not null
  2237.     begin
  2238.         raiserror(15600,-1,-1,'sp_addremotelogin')
  2239.         return (1)
  2240.     end
  2241.  
  2242.     -- VALIDATE @loginame --
  2243.     if @loginame is not null
  2244.     begin
  2245.         select @sid = sid from master.dbo.syslogins where loginname = @loginame
  2246.                     AND isntname = 0        -- cannot remap to NT login
  2247.         if @sid is null
  2248.         begin
  2249.             raiserror(15067,-1,-1,@loginame)
  2250.             return (1)
  2251.         end
  2252.     end
  2253.  
  2254.     -- CHECK FOR DUPLICATE <@remoteserver, @remotename> PAIR --
  2255.     --    (Note that this works for @remotename null and not null)
  2256.     if exists (select * from master.dbo.sysxlogins where srvid = @srvid 
  2257.                 AND ((@remotename is null AND name is null) OR name = @remotename)
  2258.                 AND isrpcinmap = 1)
  2259.     begin
  2260.         if @remotename is null
  2261.             raiserror(15066,-1,-1,@remoteserver)
  2262.         else
  2263.             raiserror(15068,-1,-1,@remotename,@remoteserver)
  2264.         return (1)
  2265.     end
  2266.  
  2267.     -- Check if there is an outgoing mapping to which we can tag on this 
  2268.     -- incoming mapping
  2269.     update master.dbo.sysxlogins set xstatus = xstatus | 32, xdate2 = getdate()
  2270.         where srvid = @srvid
  2271.         AND ((@remotename is null AND name is null) OR name = @remotename)
  2272.         AND ((@sid is null AND sid is null) OR sid = @sid)
  2273.  
  2274.     -- If update didnt happen, add an entry. (@srvid, @remotename, @sid)
  2275.     if @@rowcount = 0
  2276.         insert into master.dbo.sysxlogins
  2277.             values(@srvid, @sid, 32, getdate(), getdate(), @remotename, NULL, 0, NULL)
  2278.  
  2279.     -- SUCCESS --
  2280.     raiserror(15448,-1,-1)
  2281.     return (0)    -- sp_addremotelogin
  2282. go
  2283.  
  2284.  
  2285. checkpoint
  2286. go
  2287.  
  2288.  
  2289. raiserror(15339,-1,-1,'sp_addtype')
  2290. go
  2291. create procedure sp_addtype --- 1996/04/08 00:00
  2292. @typename sysname,        -- name of user-defined type
  2293. @phystype sysname,        -- physical system type of user-defined type
  2294. @nulltype varchar(8) = null,    -- nullability of new type
  2295. @owner sysname = null    -- Owner of type (default is caller)
  2296. as
  2297.  
  2298. declare @len int        -- length of user type
  2299. declare @type tinyint        -- typeid of physical type
  2300. declare @tlen smallint        -- length of physical type
  2301. declare @typeid smallint    -- user typeid of physical type
  2302. declare @nonull bit        -- default is getansinull()
  2303. declare @prec int        -- precision of the datatype
  2304. declare @scale int        -- scale of the datatype
  2305. declare @tprec tinyint        -- precision of the datatype read from systypes
  2306. declare @tscale tinyint        -- scale of the datatype read from systypes
  2307. declare @tname sysname  -- typename from systypes
  2308. declare @tstat tinyint      -- typestat from systypes
  2309. declare @orig_phystype    sysname
  2310.  
  2311. select @orig_phystype = @phystype
  2312. select @nulltype = rtrim(lower(@nulltype))
  2313. select @typename = rtrim(@typename)
  2314. select @phystype = lower(rtrim(@phystype))
  2315.  
  2316. -- VALIDATE THE @owner NAME (and verify caller can use this name)
  2317. declare @uid smallint
  2318. if @owner is null
  2319.     select @uid = user_id()
  2320. else 
  2321.     select @uid = uid from sysusers where name = @owner
  2322.         and isaliased = 0 AND uid NOT IN (0,3,4) --public/INFO_SCHEMA/etc can't own type
  2323. if @uid is null OR
  2324.     (is_member('db_owner')=0 AND
  2325.      is_member('db_ddladmin')=0 AND
  2326.      is_member(user_name(@uid))=0)
  2327. begin
  2328.     raiserror(15600, -1, -1, 'sp_addtype')
  2329.     return 1
  2330. end
  2331.  
  2332. -- TYPES BASED ON BIT CAN BE NULL IN SPHINX,
  2333. --    BUT MAKE NOT-NULL THE DFLT FOR BCKWRD-COMPAT
  2334. if lower(@phystype) = 'bit' and @nulltype is null
  2335.                 -- If user didn't specify nullability,
  2336.                 -- make sure it doesn't get set to nullable
  2337.                 -- by getansinull()
  2338.         select @nulltype = 'not null'
  2339.  
  2340. /*
  2341. **  Should the user type allow NULLs?
  2342. */
  2343. if @nulltype is null
  2344.     select @nonull = abs(getansinull()-1)
  2345. else if @nulltype = 'null'
  2346.     select @nonull = 0
  2347. else if @nulltype in ('not null','nonull')
  2348.     select @nonull = 1
  2349. else
  2350.     begin
  2351.         raiserror(15085,-1,-1)
  2352.         return (1)
  2353.     end
  2354.  
  2355. /*
  2356. **  Check to see that the @typename is valid.
  2357. */
  2358. declare @returncode int
  2359. execute @returncode = sp_validname @typename
  2360. if @returncode <> 0
  2361.     return(1)
  2362.  
  2363. /*
  2364. **  Check to see if the user type already exists or a system type
  2365. **  whose name = lower(@typename) (or a synomym) already exists.
  2366. */
  2367. if exists (select * from systypes where name = @typename)
  2368.         or lower(@typename)
  2369.         in ('character','character varying','char varying',
  2370.             'integer','dec','binary varying')
  2371.  
  2372.     begin
  2373.         raiserror(15029,-1,-1,@typename)
  2374.         return (1)
  2375.     end
  2376.  
  2377. /*
  2378. **  Check to see if the user type has been reserved for future use.
  2379. */
  2380. if @typename in ('variant','bigint')
  2381.     begin
  2382.         raiserror(15075,-1,-1,@typename)
  2383.         return (1)
  2384.     end
  2385.  
  2386. /*
  2387. ** Can't supply length with sysname type.
  2388. */
  2389. if @phystype like 'sysname%(%'
  2390.     begin
  2391.         raiserror(15270,-1,-1)
  2392.         return(1)
  2393.     end
  2394.  
  2395. /*
  2396. ** initialize the length to be NULL first.
  2397. */
  2398. select @len = NULL
  2399.  
  2400. /*
  2401. ** If precision and scale were given with the type - extract them
  2402. */
  2403. if @phystype like '_%(_%,_%)'
  2404. begin
  2405.     select @prec = convert(int, substring(@phystype,
  2406.         charindex('(',@phystype) + 1,
  2407.         charindex(',',@phystype) - 1 - charindex('(',@phystype)))
  2408.  
  2409.     select @scale = convert(int, substring(@phystype,
  2410.         charindex(',',@phystype) + 1,
  2411.         charindex(')',@phystype) - 1 - charindex(',',@phystype)))
  2412.     /*
  2413.     ** Extract the physical type name
  2414.     */
  2415.     select @phystype = substring(@phystype, 1,
  2416.            charindex('(', @phystype) - 1)
  2417. end
  2418. else
  2419.  
  2420. /*
  2421. **  If a length was given with the user datatype, extract it.
  2422. */
  2423. if @phystype like '_%(%)'
  2424. begin
  2425.     select @len = convert(int, substring(@phystype,
  2426.         charindex('(',@phystype) + 1,
  2427.         charindex(')',@phystype) - 1 - charindex('(',@phystype)))
  2428.  
  2429.     /*
  2430.     ** Extract the physical type name
  2431.     */
  2432.     select @phystype = substring(@phystype, 1,
  2433.            charindex('(', @phystype) - 1)
  2434. end
  2435.  
  2436. select @phystype = rtrim(@phystype)
  2437.  
  2438. if @phystype='character'
  2439.     select @phystype='char'
  2440. else if @phystype='character varying'
  2441.     select @phystype='varchar'
  2442. else if @phystype='char varying'
  2443.     select @phystype='varchar'
  2444. else if @phystype='integer'
  2445.     select @phystype='int'
  2446. else if @phystype='dec'
  2447.     select @phystype='decimal'
  2448. else if @phystype='binary varying'
  2449.     select @phystype='varbinary'
  2450.  
  2451. /*
  2452. **  Make sure that the physical type exists and get its characteristics.
  2453. **  System physical types have a xusertype < 256 and are owned by the
  2454. **  dbo (userid = 1).
  2455. */
  2456. select @type = xtype, @tlen = length,
  2457.     @tprec = xprec, @tscale = xscale, @tstat = status, @tname = name
  2458. from systypes
  2459.     where xusertype < 256 and name = @phystype and uid = 1
  2460.  
  2461. if @type is null
  2462. begin
  2463.     raiserror(15036,-1,-1,@orig_phystype)
  2464.     return (1)
  2465. end
  2466.  
  2467. /*
  2468. **  Disallow user-defined datatypes on timestamps.  This is done because
  2469. **  a timestamp is not a basic type but is really a binary.  There is,
  2470. **  therefore, no way to tell if a user-defined datatype is mapped to
  2471. **  a binary or a timestamp.  Timestamps can't have rules or defaults.
  2472. */
  2473. if @phystype = 'timestamp'
  2474. begin
  2475.     raiserror(15038,-1,-1)
  2476.     return (1)
  2477. end
  2478.  
  2479. /*
  2480. **  Check if the NULL status of the user type is consistent with the NULL status
  2481. **  of the physical type.  Here are the possible cases.
  2482. **
  2483. **           physical type
  2484. **          NULLs      NONULLs
  2485. **            -----------------
  2486. ** user    NULLs    |  ok    |  no
  2487. ** type NONULLs    |  ok    |  ok
  2488. */
  2489. -- NOT NECESSARY: bit and timestamp both already special-cased
  2490. /**********
  2491. if @nonull = 0 and 1 = 0
  2492.     begin
  2493.         raiserror(15037,-1,-1,@orig_phystype)
  2494.         return (1)
  2495.     end
  2496. **********/
  2497.  
  2498. /* Decide about precision, scale, length
  2499. ** First check from NUMERIC, DECIMAL
  2500. */
  2501. if @tname in ('numeric','decimal')
  2502. begin
  2503.     /* Type is NUMERIC or DECIMAL */
  2504.  
  2505.     if @len > 0
  2506.         begin
  2507.             /* Length is really the precision
  2508.             ** Since no scale is specified then scale
  2509.             ** is minimum(Default, precision). Default = 4
  2510.             */
  2511.             select @prec = @len
  2512.             select @scale = 0
  2513.         end
  2514.     else
  2515.         if (@prec is NULL)
  2516.             begin
  2517.                 select @prec = 18
  2518.                 select @scale = 0
  2519.             end
  2520.  
  2521.     if (@prec > 38) or (@prec < 1)
  2522.         begin
  2523.             raiserror(15086,-1,-1)
  2524.             return (1)
  2525.         end
  2526.  
  2527.     if (@scale > @prec) or (@scale < 0)
  2528.         begin
  2529.             /*
  2530.             ** Illegal scale specified -- must be less than precision
  2531.             ** and positive.
  2532.             */
  2533.             raiserror(15087,-1,-1)
  2534.             return (1)
  2535.         end
  2536.  
  2537.     /* Compute length from precision */
  2538.     if (@prec <= 9)
  2539.         select @len = 5
  2540.  
  2541.     if (@prec > 9) and (@prec <= 19)
  2542.         select @len = 9
  2543.  
  2544.     if (@prec > 19) and (@prec <= 28)
  2545.         select @len = 13
  2546.  
  2547.     if (@prec > 28) and (@prec <= 38)
  2548.         select @len = 17
  2549.  
  2550. end
  2551. else
  2552.  
  2553. /*
  2554. **  Typeids 1 (char), 2 (varchar), 3 (binary) and 4 (varbinary) are the
  2555. **  only ones which allow a length to be specified.
  2556. */
  2557. if @tname not in ('binary', 'varbinary', 'char', 'varchar', 'nchar', 'nvarchar')
  2558.     begin
  2559.         /*
  2560.         **  We can't use a length and we got one.
  2561.         */
  2562.         if @len > 0
  2563.             begin
  2564.                 raiserror(15088,-1,-1)
  2565.                 return (1)
  2566.             end
  2567.  
  2568.         /*
  2569.         **  Use the fixed length of the physical type.
  2570.         */
  2571.         select @len = @tlen
  2572.         select @prec = @tprec
  2573.         select @scale = @tscale
  2574.     end
  2575. else
  2576.     begin
  2577.         /*
  2578.         **  We need a length and we didn't get one.
  2579.         */
  2580.         if @len is null
  2581.             begin
  2582.                 raiserror(15091,-1,-1)
  2583.                 return (1)
  2584.             end
  2585.  
  2586.         -- need to adjust length for unicode (watch out for overflow!)
  2587.         if @tname in ('nchar', 'nvarchar') and (@len & 0x80000000) != 0x80000000
  2588.             select @len = @len * 2
  2589.         if @len <= 0 or @len > 8000
  2590.             begin
  2591.                 raiserror(15092,-1,-1)
  2592.                 return (1)
  2593.             end
  2594.  
  2595.         select @prec = @tprec
  2596.         select @scale = @tscale
  2597.     end
  2598.  
  2599. /*
  2600. **  Finally, get the maximum existing user type so we use it + 1 for this
  2601. **  new type.
  2602. */
  2603. select @typeid = max(xusertype)
  2604.     from systypes
  2605.  
  2606. /*
  2607. **  There are no user defined types yet so use the first number (256).
  2608. */
  2609. if @typeid < 256
  2610.     select @typeid = 256
  2611.  
  2612. -- Set null status bit
  2613. if @nonull = 1
  2614.     select @tstat = @tstat | 0x01
  2615. else
  2616.     select @tstat = @tstat & 0xFE
  2617.  
  2618. insert systypes (name, xtype, status, xusertype, length, xprec, xscale,
  2619.             tdefault, domain, uid, reserved)
  2620.     select @typename, @type, @tstat, @typeid + 1, @len, @prec, @scale,
  2621.             0, 0, @uid, 0
  2622.  
  2623. raiserror(15449,-1,-1)
  2624.  
  2625. return (0) -- sp_addtype
  2626. go
  2627.  
  2628.  
  2629. raiserror(15339,-1,-1,'sp_altermessage')
  2630. go
  2631. create procedure sp_altermessage --- 1996/04/08 00:00
  2632. @message_id       int,
  2633. @parameter        sysname,
  2634. @parameter_value  varchar(5)
  2635. as
  2636. begin
  2637.   declare @rows_affected  varchar(16)
  2638.   declare @msg            varchar(128)
  2639.  
  2640.   select @parameter = upper(@parameter)
  2641.   select @parameter_value = upper(@parameter_value)
  2642.  
  2643.   /*
  2644.   **  You must be in Sysadmin role to execute this sproc.
  2645.   */
  2646.   if (not (is_srvrolemember('sysadmin') = 1))
  2647.   begin
  2648.       raiserror(15003, 16, 1, 'sysadmin')
  2649.       return (1)
  2650.   end
  2651.  
  2652.   /*
  2653.   ** Does this message exist?
  2654.   */
  2655.   if (not exists (select * from master.dbo.sysmessages
  2656.                   where error = @message_id))
  2657.   begin
  2658.           raiserror(15179,-1,-1,@message_id)
  2659.           return (1)
  2660.   end
  2661.  
  2662.   /*
  2663.   ** Is Parameter 'WITH_LOG'?
  2664.   */
  2665.   if (@parameter <> 'WITH_LOG')
  2666.   begin
  2667.     raiserror(15176,-1,-1)
  2668.     return (1)
  2669.   end
  2670.  
  2671.   /*
  2672.   ** Is ParameterValue TRUE or FALSE?
  2673.   */
  2674.   if (@parameter_value not in ('TRUE', 'FALSE'))
  2675.   begin
  2676.           raiserror(15277,-1,-1)
  2677.           return (1)
  2678.   end
  2679.  
  2680.   /*
  2681.   ** Determine the number of messages affected
  2682.   */
  2683.   select @rows_affected = convert(varchar(16), count(*)) from master.dbo.sysmessages
  2684.        where error = @message_id
  2685.  
  2686.   /*
  2687.   ** Turn dlevel bit 7 on or off
  2688.   */
  2689.   if (@parameter_value = 'TRUE')
  2690.   begin
  2691.           update master.dbo.sysmessages
  2692.                   set dlevel = dlevel | 0x80
  2693.                           where error = @message_id
  2694.           if (@@error = 0)
  2695.           begin
  2696.             if (convert(int, @rows_affected) = 1) 
  2697.                 raiserror(15451,-1,-1, '')
  2698.             if (convert(int, @rows_affected) > 1) 
  2699.                 raiserror(15451,-1,-1, @rows_affected)
  2700.           end
  2701.   end
  2702.   else
  2703.   if (@parameter_value = 'FALSE')
  2704.   begin
  2705.           update master.dbo.sysmessages
  2706.                   set dlevel = dlevel & 0x7FFFFF7F
  2707.                           where error = @message_id
  2708.           if (@@error = 0)
  2709.           begin
  2710.             if (convert(int, @rows_affected) = 1) 
  2711.                 raiserror(15451,-1,-1, '')
  2712.             if (convert(int, @rows_affected) > 1) 
  2713.                 raiserror(15451,-1,-1, @rows_affected)
  2714.           end
  2715.   end
  2716.   return (0)
  2717. end
  2718. -- sp_altermessage
  2719. go
  2720.  
  2721. raiserror(15339,-1,-1,'sp_attach_db')
  2722. go
  2723. create procedure sp_attach_db
  2724. @dbname sysname
  2725. , @filename1 nvarchar(260)
  2726. , @filename2 nvarchar(260) = NULL
  2727. , @filename3 nvarchar(260) = NULL
  2728. , @filename4 nvarchar(260) = NULL
  2729. , @filename5 nvarchar(260) = NULL
  2730. , @filename6 nvarchar(260) = NULL
  2731. , @filename7 nvarchar(260) = NULL
  2732. , @filename8 nvarchar(260) = NULL
  2733. , @filename9 nvarchar(260) = NULL
  2734. , @filename10 nvarchar(260) = NULL
  2735. , @filename11 nvarchar(260) = NULL
  2736. , @filename12 nvarchar(260) = NULL
  2737. , @filename13 nvarchar(260) = NULL
  2738. , @filename14 nvarchar(260) = NULL
  2739. , @filename15 nvarchar(260) = NULL
  2740. , @filename16 nvarchar(260) = NULL
  2741. as
  2742. declare @execstring nvarchar (4000)
  2743. set nocount on
  2744.  
  2745.     IF ((@dbname is null OR datalength(@dbname) = 0) OR
  2746.         (@filename1 is null OR datalength(@filename1) = 0))
  2747.     begin
  2748.         raiserror (15004,-1,-1)
  2749.         return (1)
  2750.     end
  2751.  
  2752.     -- build initial CREATE DATABASE
  2753.     select @execstring = 'CREATE DATABASE ' 
  2754.         + quotename( @dbname , '[') 
  2755.         + ' ON (FILENAME ='
  2756.         + ''''
  2757.         + @filename1
  2758.         + ''''
  2759.  
  2760.     -- add any additional files
  2761.  
  2762.     if (@filename2 IS NOT NULL)
  2763.     begin
  2764.         select @execstring = @execstring 
  2765.             + ' ), (FILENAME= '''
  2766.             + @filename2 
  2767.             + ''''
  2768.     end
  2769.         
  2770.     if (@filename3 IS NOT NULL)
  2771.     begin
  2772.         select @execstring = @execstring 
  2773.             + ' ), (FILENAME= '''
  2774.             + @filename3
  2775.             + ''''
  2776.     end
  2777.         
  2778.     if (@filename4 IS NOT NULL)
  2779.     begin
  2780.         select @execstring = @execstring 
  2781.             + ' ), (FILENAME= '''
  2782.             + @filename4
  2783.             + ''''
  2784.     end
  2785.         
  2786.     if (@filename5 IS NOT NULL)
  2787.     begin
  2788.         select @execstring = @execstring 
  2789.             + ' ), (FILENAME= '''
  2790.             + @filename5
  2791.             + ''''
  2792.     end
  2793.         
  2794.     if (@filename6 IS NOT NULL)
  2795.     begin
  2796.         select @execstring = @execstring 
  2797.             + ' ), (FILENAME= '''
  2798.             + @filename6
  2799.             + ''''
  2800.     end
  2801.         
  2802.     if (@filename7 IS NOT NULL)
  2803.     begin
  2804.         select @execstring = @execstring 
  2805.             + ' ), (FILENAME= '''
  2806.             + @filename7
  2807.             + ''''
  2808.     end
  2809.         
  2810.     if (@filename8 IS NOT NULL)
  2811.     begin
  2812.         select @execstring = @execstring 
  2813.             + ' ), (FILENAME= '''
  2814.             + @filename8 
  2815.             + ''''
  2816.     end
  2817.         
  2818.     if (@filename9 IS NOT NULL)
  2819.     begin
  2820.         select @execstring = @execstring 
  2821.             + ' ), (FILENAME= '''
  2822.             + @filename9
  2823.             + ''''
  2824.     end
  2825.         
  2826.     if (@filename10 IS NOT NULL)
  2827.     begin
  2828.         select @execstring = @execstring 
  2829.             + ' ), (FILENAME= '''
  2830.             + @filename10 
  2831.             + ''''
  2832.     end
  2833.         
  2834.     if (@filename11 IS NOT NULL)
  2835.     begin
  2836.         select @execstring = @execstring 
  2837.             + ' ), (FILENAME= '''
  2838.             + @filename11 
  2839.             + ''''
  2840.     end
  2841.         
  2842.     if (@filename12 IS NOT NULL)
  2843.     begin
  2844.         select @execstring = @execstring 
  2845.             + ' ), (FILENAME= '''
  2846.             + @filename12 
  2847.             + ''''
  2848.     end
  2849.         
  2850.     if (@filename13 IS NOT NULL)
  2851.     begin
  2852.         select @execstring = @execstring 
  2853.             + ' ), (FILENAME= '''
  2854.             + @filename13 
  2855.             + ''''
  2856.     end
  2857.         
  2858.     if (@filename14 IS NOT NULL)
  2859.     begin
  2860.         select @execstring = @execstring 
  2861.             + ' ), (FILENAME= '''
  2862.             + @filename14 
  2863.             + ''''
  2864.     end
  2865.         
  2866.     if (@filename15 IS NOT NULL)
  2867.     begin
  2868.         select @execstring = @execstring 
  2869.             + ' ), (FILENAME= '''
  2870.             + @filename15
  2871.             + ''''
  2872.     end
  2873.         
  2874.     if (@filename16 IS NOT NULL)
  2875.     begin
  2876.         select @execstring = @execstring 
  2877.             + ' ), (FILENAME= '''
  2878.             + @filename16 
  2879.             + ''''
  2880.     end
  2881.         
  2882.         
  2883.     -- note it as for attach
  2884.     select @execstring = @execstring + ' ) FOR ATTACH'
  2885.     exec (@execstring)
  2886.  
  2887. if @@error <>  0
  2888.     begin
  2889.         -- No need to raiserror as the CREATE DATABASE will do so
  2890.         return(1)
  2891.     end
  2892. return (0) -- sp_attach_db
  2893. go
  2894.  
  2895.  
  2896. raiserror(15339,-1,-1,'sp_attach_single_file_db')
  2897. go
  2898. create procedure sp_attach_single_file_db
  2899. @dbname sysname,
  2900. @physname nvarchar(260)
  2901. as
  2902. declare @execstring nvarchar (400)
  2903. set nocount on
  2904.     IF ((@dbname is null OR datalength(@dbname) = 0) OR
  2905.        (@physname is null OR datalength(@physname) = 0))
  2906.     begin
  2907.         raiserror (15004,-1,-1)
  2908.         return (1)
  2909.     end
  2910.  
  2911.     select @execstring = 'CREATE DATABASE ' 
  2912.         + quotename( @dbname , '[') 
  2913.         + ' ON (FILENAME ='
  2914.         + ''''
  2915.         + @physname 
  2916.         + ''''
  2917.         + ' ) FOR ATTACH'
  2918.     exec (@execstring)
  2919. if @@error <>  0
  2920.     begin
  2921.         -- No need to raiserror as the CREATE DATABASE will do so
  2922.         return(1)
  2923.     end
  2924.     -- strip out replication from this database
  2925. if exists (select * from master.dbo.sysobjects where name=N'sp_removedbreplication')
  2926.     begin
  2927.         exec sp_removedbreplication @dbname
  2928.     end
  2929.     return (0) -- sp_attach_single_file_db
  2930. go
  2931.  
  2932.  
  2933. raiserror(15339,-1,-1,'sp_helplanguage')
  2934. go
  2935. create procedure sp_helplanguage --- 1996/04/08 00:00
  2936. @language sysname = NULL
  2937. as
  2938.  
  2939. /* Print all languages if the user didn't give the language name. */
  2940. if @language is null
  2941. begin
  2942.     if exists (select * from master.dbo.syslanguages)
  2943.         select * from master.dbo.syslanguages
  2944.     else
  2945.         raiserror(15452,-1,-1)
  2946.  
  2947.     /* Find out whether us_english is there or not. */
  2948.     if not exists (select * from master.dbo.syslanguages
  2949.             where name = 'us_english')
  2950.         raiserror(15453,-1,-1)
  2951.  
  2952.     return (0)
  2953. end
  2954.  
  2955. /*  Report information on this language. */
  2956. if exists (select * from master.dbo.syslanguages where name = @language)
  2957.     begin
  2958.         select * from master.dbo.syslanguages where name = @language
  2959.         return (0)
  2960.     end
  2961.  
  2962. if exists (select * from master.dbo.syslanguages where alias = @language)
  2963.     begin
  2964.         select * from master.dbo.syslanguages where alias = @language
  2965.         return (0)
  2966.     end
  2967.  
  2968. /* Couldn't find this language. */
  2969. if @language = 'us_english'
  2970.     begin
  2971.         raiserror(15453,-1,-1)
  2972.         return (0)
  2973.     end
  2974. else
  2975.     begin
  2976.         raiserror(15033,-1,-1,@language)
  2977.         return (1)
  2978.     end
  2979. -- sp_helplanguage
  2980. go
  2981.  
  2982.  
  2983.  
  2984.  
  2985. checkpoint
  2986. go
  2987.  
  2988. raiserror(15339,-1,-1,'sp_bindefault')
  2989. go
  2990. create procedure sp_bindefault --- 1996/08/30 20:04
  2991. @defname nvarchar(776),            /* name of the default */
  2992. @objname nvarchar(517),            /* table or usertype name */
  2993. @futureonly varchar(15) = NULL        /* flag to indicate extent of binding */
  2994. as
  2995.  
  2996. declare @defid int            /* id of the default to bind */
  2997. declare @futurevalue varchar(15)    /* the value of @futureonly that causes
  2998.                     ** the binding to be limited */
  2999. declare
  3000.     @vc1            nvarchar(517)
  3001.     ,@tab_id        integer
  3002.     ,@parent_obj    integer
  3003.     ,@cur_tab_id    integer
  3004.     ,@colid            smallint
  3005.     ,@xtype            tinyint
  3006.     ,@xusertype        smallint
  3007.     ,@col_status    tinyint
  3008.     ,@col_default int
  3009.     ,@identity binary(1)
  3010.     
  3011. declare
  3012.     @UnqualDef            sysname
  3013.     ,@QualDef1            sysname
  3014.     ,@QualDef2            sysname
  3015.     ,@QualDef3            sysname
  3016.  
  3017.     ,@UnqualObj            sysname
  3018.     ,@QualObj1            sysname
  3019.     ,@QualObj2            sysname
  3020.     ,@QualObj3            sysname
  3021.  
  3022. set cursor_close_on_commit    off
  3023. set nocount            on
  3024.  
  3025. select @futurevalue = 'futureonly'    /* initialize @futurevalue */
  3026. select @identity = 0X80 /* identity columns*/
  3027.  
  3028. /*
  3029. **  When a default or rule is bound to a user-defined datatype, it is also
  3030. **  bound, by default, to any columns of the user datatype that are currently
  3031. **  using the existing default or rule as their default or rule.  This default
  3032. **  action may be overridden by setting @futureonly = @futurevalue when the
  3033. **  procedure is invoked.  In this case existing columns with the user
  3034. **  datatype won't have their existing default or rule changed.
  3035. */
  3036.  
  3037. -- get name parts --
  3038. select @UnqualDef = parsename(@defname, 1),
  3039.         @QualDef1 = parsename(@defname, 2),
  3040.         @QualDef2 = parsename(@defname, 3),
  3041.         @QualDef3 = parsename(@defname, 4)
  3042.  
  3043. select @UnqualObj = parsename(@objname, 1),
  3044.         @QualObj1 = parsename(@objname, 2),
  3045.         @QualObj2 = parsename(@objname, 3),
  3046.         @QualObj3 = parsename(@objname, 4)
  3047.  
  3048. IF (@UnqualDef is NULL OR @QualDef3 is not null)
  3049.    begin
  3050.    raiserror(15253,-1,-1,@defname)
  3051.    return (1)
  3052.    end
  3053.  
  3054. IF (@UnqualObj is NULL OR @QualObj3 is not null)
  3055.    begin
  3056.    raiserror(15253,-1,-1,@objname)
  3057.    return (1)
  3058.    end
  3059.  
  3060.  
  3061. ------------------  Verify database.
  3062.  
  3063. if ((@QualObj2 is not null and @QualObj1 is null)
  3064.     or (@QualDef2 is not null and @QualDef2 <> db_name()))
  3065.     begin
  3066.         raiserror(15076,-1,-1)
  3067.         return (1)
  3068.     end
  3069.  
  3070. /*
  3071. **  Check that the @futureonly argument, if supplied, is correct.
  3072. */
  3073. if (@futureonly IS NOT NULL)
  3074.     if (@futureonly <> @futurevalue)
  3075.         begin
  3076.             raiserror(15100,-1,-1)
  3077.             return (1)
  3078.         end
  3079.  
  3080. /*
  3081. **  Check to see that the default exists and get its id.
  3082. */
  3083. select @defid = id, @parent_obj = parent_obj from sysobjects
  3084.             where id = object_id(@defname)
  3085.                 and xtype='D '    -- default object 6
  3086.  
  3087. if @defid is NULL
  3088.     begin
  3089.         raiserror(15016,-1,-1,@UnqualDef)
  3090.         return (1)
  3091.     end
  3092.  
  3093.  
  3094. if @parent_obj > 0
  3095.     begin
  3096.         raiserror(15050,-1,-1,@defname)
  3097.         return(1)
  3098.     end
  3099.  
  3100. /*
  3101. **  If @objname is of the form tab.col then we are binding to a column.
  3102. **  Otherwise its a datatype.  In the column case, we need to extract
  3103. **  and verify the table and column names and make sure the user owns
  3104. **  the table that is getting the default bound. We also need to ensure
  3105. **  that we don't overwrite any DRI style defaults.
  3106. */
  3107. if @QualObj1 is not null
  3108. begin
  3109.     if (@QualObj2 is not null)
  3110.         select @vc1 = QuoteName(@QualObj2) + '.' + QuoteName(@QualObj1)
  3111.     else
  3112.         select @vc1 = QuoteName(@QualObj1)
  3113.  
  3114.     select    @tab_id = o.id,        @colid = c.colid, 
  3115.             @xtype = c.xtype,    @col_status = c.status,
  3116.             @col_default = c.cdefault
  3117.     from sysobjects o, syscolumns c 
  3118.     where c.id = object_id(@vc1,'local')
  3119.             and c.name = @UnqualObj
  3120.             and o.id = c.id
  3121.             and o.xtype='U '
  3122.  
  3123.     /*Check that table and column exist*/
  3124.      if @tab_id is null
  3125.     begin
  3126.         raiserror(15104,-1,-1,@QualObj1,@UnqualObj)
  3127.         return (1)
  3128.     end
  3129.  
  3130.     /*
  3131.     **  If the column type is timestamp, disallow the bind.
  3132.     **  Defaults can't be bound to timestamp columns.
  3133.     */
  3134.     if type_name(@xtype) = 'timestamp'
  3135.     begin
  3136.         raiserror(15101,-1,-1)
  3137.         return (1)
  3138.     end
  3139.  
  3140.     /*
  3141.     **  If the column category is identity, disallow the bind.
  3142.     **  Defaults can't be bound to identity columns.
  3143.     */
  3144.     if @col_status & @identity = @identity
  3145.     begin
  3146.         raiserror(15102,-1,-1)
  3147.         return (1)
  3148.     end
  3149.  
  3150.    /*
  3151.    **  Check to see if the column was created with or altered
  3152.    **  to have a DRI style default value.
  3153.    */
  3154.     if @col_default > 0
  3155.         if exists
  3156.          (select    *
  3157.             from    sysobjects o
  3158.             where    @col_default       = o.id
  3159.             and        @tab_id             = o.parent_obj)
  3160.         begin
  3161.             raiserror(15103,-1,-1)
  3162.             return (1)
  3163.         end
  3164.  
  3165.     BEGIN TRANSACTION txn_bindefault_1
  3166.  
  3167.         /*
  3168.         **  Since binding a default is a schema change, update schema count
  3169.         **  for the object in the sysobjects table.
  3170.         */
  3171.  
  3172.         dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  3173.  
  3174.         update syscolumns set cdefault = @defid where id = @tab_id and colid = @colid
  3175.  
  3176.     COMMIT TRANSACTION txn_bindefault_1
  3177.  
  3178.     raiserror(15511,-1,-1)
  3179.  
  3180. end
  3181. else
  3182. begin
  3183.     /*
  3184.     **  We're binding to a user type.  In this case, the @objname
  3185.     **  is really the name of the user datatype.
  3186.     **  When we bind to a user type, any existing columns get changed
  3187.     **  to the new binding unless their current binding is not equal
  3188.     **  to the current binding for the usertype or if they set the
  3189.     **  @futureonly parameter to @futurevalue.
  3190.     */
  3191.     declare @olddefault int    /* current default for type */
  3192.  
  3193.     /*
  3194.     **  Get the current default for the datatype.
  3195.     */
  3196.  
  3197.     select @xusertype = xusertype, @olddefault = tdefault
  3198.         from systypes where name = @UnqualObj and xusertype > 256
  3199.         AND (is_member('db_owner') = 1 OR is_member('db_ddladmin') = 1 OR is_member(user_name(uid))=1)
  3200.  
  3201.     if @xusertype is null
  3202.         begin
  3203.             raiserror(15105,-1,-1)
  3204.             return (1)
  3205.         end
  3206.  
  3207.     update systypes
  3208.         set tdefault = @defid
  3209.             from systypes
  3210.         where xusertype = @xusertype
  3211.  
  3212.  
  3213.     raiserror(15512,-1,-1)
  3214.  
  3215.     /*
  3216.     **  need the new binding.
  3217.     */
  3218.     if isnull(@futureonly, ' ') <> @futurevalue
  3219.     begin
  3220.  
  3221.         declare csr3_t1 insensitive cursor for
  3222.           select
  3223.             distinct
  3224.                  c.id
  3225.                  ,c.colid
  3226.             from     syscolumns    c JOIN sysobjects o ON c.id = o.id AND o.xtype = 'U '
  3227.             where     c.xusertype    = @xusertype
  3228.             and    (c.cdefault    = @olddefault    OR
  3229.                  c.cdefault    = 0
  3230.                 )
  3231.             order by c.id
  3232.                   for read only
  3233.  
  3234.         open csr3_t1
  3235.  
  3236.         BEGIN TRANSACTION txn_bindefault_3
  3237.  
  3238.         fetch next from csr3_t1 into
  3239.              @tab_id,
  3240.              @colid
  3241.  
  3242.         WHILE @@fetch_status = 0
  3243.         begin
  3244.  
  3245.             select @vc1 = quotename(user_name(OBJECTPROPERTY(@tab_id,'OwnerId'))) + '.' 
  3246.                         + quotename(object_name(@tab_id))
  3247.  
  3248.             dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  3249.  
  3250.             select @cur_tab_id = @tab_id
  3251.  
  3252.             while @cur_tab_id = @tab_id and @@fetch_status = 0
  3253.             begin
  3254.  
  3255.                 update syscolumns
  3256.                 set cdefault = @defid
  3257.                 from syscolumns c
  3258.                 where c.id = @tab_id
  3259.                 and c.colid = @colid
  3260.  
  3261.                 fetch next from csr3_t1 into
  3262.                      @tab_id,
  3263.                      @colid
  3264.             end
  3265.  
  3266.         end --loop 3
  3267.  
  3268.         COMMIT TRANSACTION txn_bindefault_3
  3269.  
  3270.         deallocate csr3_t1
  3271.  
  3272.         raiserror(15513,-1,-1)
  3273.     end
  3274. end
  3275.  
  3276. return (0) -- sp_bindefault
  3277. go
  3278.  
  3279. raiserror(15339,-1,-1,'sp_bindrule')
  3280. go
  3281. create procedure sp_bindrule --- 1996/08/14 15:02
  3282. @rulename nvarchar(776),            /* name of the rule */
  3283. @objname nvarchar(517),            /* table or usertype name */
  3284. @futureonly varchar(15) = NULL        /* column name */
  3285. as
  3286.  
  3287. declare @ruleid int            /* id of the rule to bind */
  3288. declare @futurevalue varchar(15)    /* the value of @futureonly that causes
  3289.                     ** the binding to be limited */
  3290.  
  3291. declare 
  3292.     @vc1            nvarchar(517)
  3293.     ,@tab_id        integer
  3294.     ,@cur_tab_id    integer
  3295.     ,@colid            smallint
  3296.  
  3297.     ,@xtype            smallint
  3298.     ,@xusertype        smallint
  3299.  
  3300. declare 
  3301.     @UnqualRule        sysname
  3302.     ,@QualRule1        sysname
  3303.     ,@QualRule2        sysname
  3304.     ,@QualRule3        sysname
  3305.  
  3306.     ,@UnqualObj        sysname
  3307.     ,@QualObj1        sysname
  3308.     ,@QualObj2        sysname
  3309.     ,@QualObj3        sysname
  3310.  
  3311. set cursor_close_on_commit    off
  3312. set nocount on
  3313.  
  3314. select @futurevalue = 'futureonly'    /* initialize @futurevalue */
  3315.  
  3316. /*
  3317. **  When a default or rule is bound to a user-defined datatype, it is also
  3318. **  bound, by default, to any columns of the user datatype that are currently
  3319. **  using the existing default or rule as their default or rule.  This default
  3320. **  action may be overridden by setting @futureonly = @futurevalue when the
  3321. **  procedure is invoked.  In this case existing columns with the user
  3322. **  datatype won't have their existing default or rule changed.
  3323. */
  3324.  
  3325. -- get name parts --
  3326. select @UnqualRule = parsename(@rulename, 1),
  3327.         @QualRule1 = parsename(@rulename, 2),
  3328.         @QualRule2 = parsename(@rulename, 3),
  3329.         @QualRule3 = parsename(@rulename, 4)
  3330.  
  3331. select @UnqualObj = parsename(@objname, 1),
  3332.         @QualObj1 = parsename(@objname, 2),
  3333.         @QualObj2 = parsename(@objname, 3),
  3334.         @QualObj3 = parsename(@objname, 4)
  3335.  
  3336. IF (@UnqualRule is NULL OR @QualRule3 is not null)
  3337.    begin
  3338.    raiserror(15253,-1,-1,@rulename)
  3339.    return (1)
  3340.    end
  3341.  
  3342. IF (@UnqualObj is NULL OR @QualObj3 is not null)
  3343.    begin
  3344.    raiserror(15253,-1,-1,@objname)
  3345.    return (1)
  3346.    end
  3347.  
  3348.  
  3349. ------------------  Verify database.
  3350.  
  3351. if ((@QualObj2 is not null and @QualObj1 is null)
  3352.     or (@QualRule2 is not null and @QualRule2 <> db_name()))
  3353.     begin
  3354.         raiserror(15077,-1,-1)
  3355.         return (1)
  3356.     end
  3357.  
  3358. /*
  3359. **  Check that the @futureonly argument, if supplied, is correct.
  3360. */
  3361. if (@futureonly IS NOT NULL)
  3362.     begin
  3363.         if (@futureonly <> @futurevalue)
  3364.             begin
  3365.                 raiserror(15106,-1,-1)
  3366.                 return (1)
  3367.             end
  3368.     end
  3369.  
  3370. /*
  3371. **  Check to see that the rule exists and get its id.
  3372. */
  3373. select @ruleid = id from sysobjects
  3374.             where id = object_id(@rulename)
  3375.                 and xtype='R ' --rule object 7
  3376.  
  3377. if @ruleid is NULL
  3378.     begin
  3379.         raiserror(15017,-1,-1,@rulename)
  3380.         return (1)
  3381.     end
  3382.  
  3383. /*
  3384. **  If @objname is of the form tab.col then we are binding to a column.
  3385. **  Otherwise its a datatype.  In the column case, we need to extract
  3386. **  and verify the table and column names and make sure the user owns
  3387. **  the table that is getting the rule bound.
  3388. */
  3389. if @QualObj1 is not null
  3390. begin
  3391.     if (@QualObj2 is not null)
  3392.         select @vc1 = QuoteName(@QualObj2) + '.' + QuoteName(@QualObj1)
  3393.     else
  3394.         select @vc1 = QuoteName(@QualObj1)
  3395.  
  3396.     select @tab_id = o.id, @colid = c.colid, @xtype = c.xtype
  3397.     from sysobjects o, syscolumns c 
  3398.     where c.id = object_id(@vc1,'local')
  3399.             and c.name = @UnqualObj
  3400.             and o.id = c.id
  3401.             and o.xtype='U '
  3402.  
  3403.     /*Check that table and column exist*/
  3404.      if @tab_id is null
  3405.     begin
  3406.         raiserror(15104,-1,-1,@QualObj1,@UnqualObj)
  3407.         return (1)
  3408.     end
  3409.  
  3410.     /*
  3411.     **  If the column type is image, text, or timestamp, disallow the bind.
  3412.     **  Rules can't be bound to image, text, or timestamp columns.
  3413.     **  The types are checked in case
  3414.     **  there is a user-defined datatype that is an image or text.
  3415.     **  User-defined datatypes mapping to timestamp are not allowed
  3416.     **  by sp_addtype.
  3417.     */
  3418.     if type_name(@xtype) in ('text', 'ntext', 'image', 'timestamp')
  3419.         begin
  3420.             raiserror(15107,-1,-1)
  3421.             return (1)
  3422.         end
  3423.  
  3424.     BEGIN TRANSACTION txn_bindrule_1
  3425.  
  3426.         dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  3427.  
  3428.         update syscolumns set domain = @ruleid
  3429.             where id = @tab_id and colid = @colid
  3430.  
  3431.     COMMIT TRANSACTION txn_bindrule_1
  3432.  
  3433.     raiserror(15514,-1,-1)
  3434.  
  3435. end
  3436. else
  3437. begin
  3438.     /*
  3439.     **  We're binding to a user type.  In this case, the @objname
  3440.     **  is really the name of the user datatype.
  3441.     **  When we bind to a user type, any existing columns get changed
  3442.     **  to the new binding unless their current binding is not equal
  3443.     **  to the current binding for the usertype or if they set the
  3444.     **  @futureonly parameter to @futurevalue.
  3445.     */
  3446.     declare @oldrule int            /* current rule for type */
  3447.  
  3448.     /*
  3449.     **  Get the current rule for the datatype.
  3450.     */
  3451.     select @oldrule = domain, @xtype = xtype, @xusertype = xusertype
  3452.         from systypes where name = @UnqualObj and xusertype > 256
  3453.         AND (is_member('db_owner') = 1 OR is_member('db_ddladmin') = 1 OR is_member(user_name(uid))=1)
  3454.  
  3455.     if @oldrule is null
  3456.         begin
  3457.             raiserror(15105,-1,-1)
  3458.             return (1)
  3459.         end
  3460.  
  3461.     /*
  3462.     **  If the column type is image, text, or timestamp, disallow the bind.
  3463.     **  Rules can't be bound to image or text columns.
  3464.     */
  3465.     if type_name(@xtype) in ('text', 'ntext', 'image', 'timestamp')
  3466.         begin
  3467.             raiserror(15107,-1,-1)
  3468.             return (1)
  3469.         end
  3470.  
  3471.     update systypes set domain = @ruleid
  3472.             from systypes
  3473.         where xusertype = @xusertype
  3474.  
  3475.  
  3476.     raiserror(15515,-1,-1)
  3477.  
  3478.     /*
  3479.     **  Now see if there are any columns with the usertype that
  3480.     **  need the new binding.
  3481.     */
  3482.     if isnull(@futureonly, ' ') <> @futurevalue
  3483.     begin
  3484.         declare csr_bindrule_1 insensitive cursor for
  3485.           select
  3486.             distinct
  3487.                  c.id
  3488.                 ,c.colid
  3489.             from     syscolumns c JOIN sysobjects o ON c.id = o.id AND o.xtype = 'U '
  3490.             where     c.xusertype    = @xusertype
  3491.             and    (c.domain    = @oldrule    OR
  3492.                  c.domain    = 0
  3493.                 )
  3494.             order by c.id
  3495.                   for read only
  3496.  
  3497.         open csr_bindrule_1
  3498.  
  3499.         BEGIN TRANSACTION txn_bindrule_2
  3500.  
  3501.         fetch next from csr_bindrule_1 into
  3502.             @tab_id
  3503.             ,@colid
  3504.  
  3505.         WHILE @@fetch_status = 0
  3506.         begin
  3507.  
  3508.             select @vc1 = quotename(user_name(OBJECTPROPERTY(@tab_id,'OwnerId'))) + '.' 
  3509.                         + quotename(object_name(@tab_id))
  3510.  
  3511.             dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  3512.  
  3513.             select @cur_tab_id = @tab_id
  3514.  
  3515.             while @cur_tab_id = @tab_id and @@fetch_status = 0
  3516.             begin
  3517.                 /*
  3518.                 **  Update syscolumns with new binding.
  3519.                 */
  3520.                 update syscolumns
  3521.                     set domain = @ruleid
  3522.                     where id = @tab_id and colid = @colid
  3523.  
  3524.                 fetch next from csr_bindrule_1 into
  3525.                      @tab_id
  3526.                     ,@colid
  3527.             end
  3528.  
  3529.         end --loop 3
  3530.  
  3531.         deallocate csr_bindrule_1
  3532.  
  3533.         COMMIT TRANSACTION txn_bindrule_2
  3534.  
  3535.         raiserror(15516,-1,-1)
  3536.     end
  3537. end
  3538. return (0) -- sp_bindrule
  3539. go
  3540.  
  3541. raiserror(15339,-1,-1,'sp_checknames')
  3542. go
  3543. create procedure sp_checknames --- 1996/04/08 00:00
  3544. @mode varchar(20) = NULL        /* mode of operation; e.g. 'silent' */
  3545. as
  3546.  
  3547. declare @msilent    int        /* set to 1 if 'silent' mode is on */
  3548. declare @ret_val    int        /* set to 1 if we find funny char */
  3549. declare @codepoint    tinyint        /* set to 1 if we find funny char */
  3550. declare @dbname        sysname    /* holds database name */
  3551. declare @msg        varchar(90)    /* used for messages to 
  3552.  */
  3553. declare @pat        varchar(132)    /* holds the pattern to search for */
  3554.  
  3555. set nocount on
  3556.  
  3557. if (@mode like '%help%')
  3558. begin
  3559.     raiserror(15525,-1,-1)
  3560.     raiserror(15526,-1,-1)
  3561.     raiserror(15527,-1,-1)
  3562.     print ' '
  3563.     raiserror(15528,-1,-1)
  3564.     raiserror('        sysdatabases.name',0,1)
  3565.     raiserror('        sysdevices.name' ,0,1)
  3566.     raiserror('        syslogins.name' ,0,1)
  3567.     raiserror('        syslogins.dbname',0,1)
  3568.     raiserror('        sysremotelogins.remoteusername',0,1)
  3569.     raiserror('        sysservers.srvname',0,1)
  3570.     raiserror('        sysservers.srvnetname',0,1)
  3571.     print ' '
  3572.     raiserror(15536,-1,-1)
  3573.     raiserror('        syscolumns.name',0,1)
  3574.     raiserror('        sysindexes.name',0,1)
  3575.     raiserror('        sysobjects.name',0,1)
  3576.     raiserror('        syssegments.name',0,1)
  3577.     raiserror('        systypes.name',0,1)
  3578.     raiserror('        sysusers.name',0,1)
  3579.     print ' '
  3580.     return (0)
  3581. end
  3582.  
  3583. /*
  3584. **  First, initialize return value, and set up mode variables:
  3585. */
  3586. select @ret_val = 0
  3587.  
  3588. if (@mode like '%silent%')
  3589.     select @msilent = 1
  3590. else
  3591.     select @msilent = 0
  3592.  
  3593.  
  3594. /*
  3595. **  Now, initialize the pattern string we will search for:
  3596. */
  3597. select @pat = '%[', @codepoint = 127
  3598. while (@codepoint < 255)
  3599. begin
  3600.     select @codepoint = @codepoint + 1
  3601.     select @pat = @pat + char(@codepoint)
  3602. end
  3603. select @pat = @pat + ']%'
  3604.  
  3605.  
  3606. /*
  3607. **  Get the database name we are in:
  3608. */
  3609. select @dbname = db_name()
  3610.  
  3611. if (@msilent = 0)
  3612. begin
  3613.     print ' '
  3614.     raiserror(15543,-1,-1,@dbname)
  3615.     print ' '
  3616. end
  3617.  
  3618.  
  3619. /*
  3620. **  Look through these only if in the master database:
  3621. */
  3622. if (@dbname = 'master')
  3623. begin
  3624.     if exists (select name from master.dbo.sysdatabases
  3625.             where convert(varchar(132), name) like @pat)
  3626.     begin
  3627.     if (@msilent = 1)
  3628.         return (1)
  3629.  
  3630.     select @ret_val = 1
  3631.     print ' '
  3632.     print '==============================================================='
  3633.     raiserror(15544,-1,-1,'sysdatabases.name')
  3634.     print ' '
  3635.     raiserror(15545,-1,-1)
  3636.     raiserror(15546,-1,-1,'sp_renamedb')
  3637.     print ' '
  3638.     select dbid,name from master.dbo.sysdatabases
  3639.             where convert(varchar(132), name) like @pat
  3640.     end
  3641.  
  3642.     if exists (select name from master.dbo.sysdevices where convert(varchar(132), name) like @pat)
  3643.     begin
  3644.     if (@msilent = 1)
  3645.         return (1)
  3646.  
  3647.     select @ret_val = 1
  3648.     print ' '
  3649.     print '==============================================================='
  3650.     raiserror(15544,-1,-1,'sysdevices.name')
  3651.     print ' '
  3652.     raiserror(15564,-1,-1)
  3653.     raiserror(15546,-1,-1,'UPDATE')
  3654.         print ' '
  3655.     select name from master.dbo.sysdevices where convert(varchar(132), name) like @pat
  3656.     end
  3657.  
  3658.     if exists (select loginname from master.dbo.syslogins where convert(varchar(132), loginname) like @pat)
  3659.     begin
  3660.     if (@msilent = 1)
  3661.         return (1)
  3662.  
  3663.     select @ret_val = 1
  3664.     print ' '
  3665.     print '==============================================================='
  3666.     raiserror(15544,-1,-1,'syslogins.name')
  3667.         print ' '
  3668.     raiserror(15565,-1,-1)
  3669.     raiserror(15546,-1,-1, 'sp_droplogin'' and ''sp_addlogin')
  3670.         print ' '
  3671.     select sid, loginname from master.dbo.syslogins
  3672.             where convert(varchar(132), loginname) like @pat
  3673.     end
  3674.  
  3675.     if exists (select dbname from master.dbo.syslogins
  3676.             where convert(varchar(132), dbname) like @pat)
  3677.     begin
  3678.     if (@msilent = 1)
  3679.         return (1)
  3680.  
  3681.     select @ret_val = 1
  3682.     print ' '
  3683.     print '==============================================================='
  3684.     raiserror(15544,-1,-1,'syslogins.dbname')
  3685.     print ' '
  3686.     raiserror(15547,-1,-1)
  3687.     raiserror(15548,-1,-1)
  3688.     raiserror(15549,-1,-1)
  3689.         print ' '
  3690.     select sid,loginname,dbname from master.dbo.syslogins
  3691.             where convert(varchar(132), dbname) like @pat
  3692.     end
  3693.  
  3694.     if exists (select remoteusername from master.dbo.sysremotelogins
  3695.             where convert(varchar(132), remoteusername) like @pat)
  3696.     begin
  3697.     if (@msilent = 1)
  3698.         return (1)
  3699.  
  3700.     select @ret_val = 1
  3701.     print ' '
  3702.     print '==============================================================='
  3703.     raiserror(15544,-1,-1,'sysremotelogins.remoteusername')
  3704.         print ' '
  3705.     raiserror(15566,-1,-1)
  3706.     raiserror(15546,-1,-1,'sp_dropremotelogin'' and ''sp_addremotelogin')
  3707.         print ' '
  3708.     select remoteserverid,remoteusername from master.dbo.sysremotelogins
  3709.             where convert(varchar(132), remoteusername) like @pat
  3710.     end
  3711.  
  3712.     if exists (select srvname from master.dbo.sysservers
  3713.             where convert(varchar(132), srvname) like @pat)
  3714.     begin
  3715.     if (@msilent = 1)
  3716.         return (1)
  3717.  
  3718.     select @ret_val = 1
  3719.     print ' '
  3720.     print '==============================================================='
  3721.     raiserror(15544,-1,-1,'sysservers.srvname')
  3722.         print ' '
  3723.     raiserror(15567,-1,-1)
  3724.     raiserror(15546,-1,-1,'sp_dropserver'' and ''sp_addserver')
  3725.         print ' '
  3726.     select srvid,srvname from master.dbo.sysservers
  3727.             where convert(varchar(132), srvname) like @pat
  3728.     end
  3729.  
  3730.     if exists (select srvnetname from master.dbo.sysservers
  3731.             where convert(varchar(132), srvnetname) like @pat)
  3732.     begin
  3733.     if (@msilent = 1)
  3734.         return (1)
  3735.  
  3736.     select @ret_val = 1
  3737.     print ' '
  3738.     print '==============================================================='
  3739.     raiserror(15544,-1,-1,'sysservers.srvnetname')
  3740.         print ' '
  3741.     raiserror(15550,-1,-1)
  3742.     raiserror(15551,-1,-1)
  3743.     raiserror(15552,-1,-1)
  3744.         print ' '
  3745.     select srvid,srvname,srvnetname from master.dbo.sysservers
  3746.             where convert(varchar(132), srvnetname) like @pat
  3747.     end
  3748.  
  3749. end
  3750.  
  3751.  
  3752. /*
  3753. **  For *ALL* databases, we want to look through these:
  3754. */
  3755. if exists (select name from dbo.syscolumns
  3756.         where convert(varchar(132), name) like @pat)
  3757. begin
  3758.     if (@msilent = 1)
  3759.     return (1)
  3760.  
  3761.     select @ret_val = 1
  3762.     print ' '
  3763.     print '==============================================================='
  3764.     raiserror(15544,-1,-1,'syscolumns.name')
  3765.     print ' '
  3766.     raiserror(15568,-1,-1)
  3767.     raiserror(15546,-1,-1,'sp_rename')
  3768.     print ' '
  3769.     select objname=o.name,colname=c.name from dbo.syscolumns c, dbo.sysobjects o
  3770.         where convert(varchar(132), c.name) like @pat and o.id = c.id
  3771. end
  3772.  
  3773. if exists (select name from dbo.sysindexes
  3774.         where convert(varchar(132), name) like @pat
  3775.               and indid > 0)
  3776. begin
  3777.     if (@msilent = 1)
  3778.     return (1)
  3779.  
  3780.     select @ret_val = 1
  3781.     print ' '
  3782.     print '==============================================================='
  3783.     raiserror(15544,-1,-1,'sysindexes.name')
  3784.     print ' '
  3785.     raiserror(15569,-1,-1)
  3786.     raiserror(15546,-1,-1,'UPDATE')
  3787.     print ' '
  3788.     select id,indid,name from dbo.sysindexes
  3789.         where convert(varchar(132), name) like @pat
  3790.         and indid > 0
  3791. end
  3792.  
  3793. if exists (select name from dbo.sysobjects
  3794.         where convert(varchar(132), name) like @pat)
  3795. begin
  3796.     if (@msilent = 1)
  3797.     return (1)
  3798.  
  3799.     select @ret_val = 1
  3800.     print ' '
  3801.     print '==============================================================='
  3802.     raiserror(15544,-1,-1,'sysobjects.name')
  3803.     print ' '
  3804.     raiserror(15570,-1,-1)
  3805.     raiserror(15546,-1,-1,'sp_rename')
  3806.     print ' '
  3807.     select owner = u.name,o.name from dbo.sysobjects o,dbo.sysusers u
  3808.         where convert(varchar(132), o.name) like @pat and o.uid=u.uid
  3809. end
  3810.  
  3811. if exists (select name from dbo.syssegments
  3812.         where convert(varchar(132), name) like @pat)
  3813. begin
  3814.     if (@msilent = 1)
  3815.     return (1)
  3816.  
  3817.     select @ret_val = 1
  3818.     print ' '
  3819.     print '==============================================================='
  3820.     raiserror(15544,-1,-1,'syssegments.name')
  3821.     print ' '
  3822.     raiserror(15571,-1,-1)
  3823.     raiserror(15546,-1,-1,'UPDATE')
  3824.     print ' '
  3825.     select segment,name from dbo.syssegments
  3826.         where convert(varchar(132), name) like @pat
  3827. end
  3828.  
  3829. if exists (select name from dbo.systypes
  3830.         where convert(varchar(132), name) like @pat)
  3831. begin
  3832.     if (@msilent = 1)
  3833.     return (1)
  3834.  
  3835.     select @ret_val = 1
  3836.     print ' '
  3837.     print '==============================================================='
  3838.     raiserror(15544,-1,-1,'systypes.name')
  3839.     print ' '
  3840.     raiserror(15572,-1,-1)
  3841.     raiserror(15546,-1,-1,'sp_rename')
  3842.     print ' '
  3843.     select name from dbo.systypes
  3844.         where convert(varchar(132), name) like @pat
  3845. end
  3846.  
  3847. if exists (select name from dbo.sysusers where convert(varchar(132), name) like @pat)
  3848. begin
  3849.     if (@msilent = 1)
  3850.     return (1)
  3851.  
  3852.     select @ret_val = 1
  3853.     print ' '
  3854.     print '==============================================================='
  3855.     raiserror(15544,-1,-1,'sysusers.name')
  3856.     print ' '
  3857.     raiserror(15573,-1,-1)
  3858.     raiserror(15546,-1,-1,'UPDATE')
  3859.     print ' '
  3860.     select sid,uid,name from dbo.sysusers
  3861.         where convert(varchar(132), name) like @pat
  3862. end
  3863.  
  3864. if (@ret_val = 0  and  @msilent = 0)
  3865. begin
  3866.  
  3867.     raiserror(15553,-1,-1, @dbname)
  3868.     raiserror(15554,-1,-1)
  3869. end
  3870.  
  3871. return (@ret_val) -- sp_checknames
  3872. go
  3873.  
  3874. checkpoint
  3875. go
  3876.  
  3877. raiserror(15339,-1,-1,'sp_MSget_current_activity')
  3878. go
  3879. -- =============================================
  3880. -- sp_MSget_current_activity
  3881. -- =============================================
  3882. create procedure dbo.sp_MSget_current_activity @id int = 0, @option int = 0, @obj nvarchar(386) = null, @spid int = 0
  3883. as
  3884.  
  3885. if (@id = 0)
  3886. begin
  3887.     raiserror(N'No SPID specified (spid = %d)', 1, 1, @id)
  3888.     return(-1)
  3889. end
  3890.  
  3891. if (@option <= 0 or @option > 5)
  3892. begin
  3893.     raiserror(N'Invalid option %d', 1, 1, @option)
  3894.     return(-1)
  3895. end
  3896.  
  3897. declare @stmt as nvarchar(4000)
  3898.  
  3899. -- =============================================
  3900. -- make tables SPID depended
  3901. -- =============================================
  3902. declare @locktab as sysname
  3903. declare @proctab as sysname
  3904.  
  3905. set @locktab = N'##lockinfo' + rtrim(convert(nvarchar(5), @id))
  3906. set @proctab = N'##procinfo' + rtrim(convert(nvarchar(5), @id))
  3907.  
  3908. if (@option = 1)
  3909. begin
  3910.     -- process info (overview of all processes by SPID)
  3911.     set @stmt = N'select [Process ID], [User], [Database], [Status], [Open Transactions], [Command], [Application], [Wait Time], [Wait Type], [Wait Resource], [CPU], [Physical IO], [Memory Usage], [Login Time], [Last Batch], [Host], [Net Library], [Net Address], [Blocked By], [Blocking] from ' + @proctab + ' order by [Process ID]'
  3912. end
  3913. else if (@option = 2)
  3914. begin
  3915.     -- distinct spid list (old)
  3916.     -- set @stmt = N'select [Process ID], [Blocking], [Blocked By] from ' @proctab + ' order by [Process ID]'
  3917.  
  3918.     -- distinct spid list, only spids with locks
  3919.     set @stmt = N'select distinct L.[Process ID], P.[Blocking], P.[Blocked By] from ' + @locktab + ' L, ' + @proctab + ' P where L.[Process ID] = P.[Process ID] order by L.[Process ID]'
  3920. end
  3921. else if (@option = 3)
  3922. begin
  3923.     -- distinct object list
  3924.     set @stmt = N'select distinct [Object] from ' + @locktab + ' order by [Object]'
  3925. end
  3926. else if (@option = 4)
  3927. begin
  3928.     -- locks per spid
  3929.     if (@spid = 0)
  3930.     begin
  3931.         raiserror(N'Error @spid parameter not specified (option %d)', 1, 1, @option)
  3932.         return(-1)
  3933.     end
  3934.     set @stmt = N'select [Object], [Lock Type], [Mode], [Status], [Owner], [Index], [Resource] from ' + @locktab + ' where [Process ID] = ' + rtrim(convert(nvarchar(10), @spid)) + ' order by [Object]'
  3935. end
  3936. else if (@option = 5)
  3937. begin
  3938.     -- locks per object
  3939.     if (@obj is null)
  3940.     begin
  3941.         raiserror(N'Error @obj parameter not specified (option %d)', 1, 1, @option)
  3942.         return(-1)
  3943.     end
  3944.     -- locked object is db
  3945.     if parsename(@obj,3) is null
  3946.     begin
  3947.         set @stmt = N'select [Process ID], [Lock Type], [Mode], [Status], [Owner], [Index], [Resource] from ' + @locktab + ' where [Object] = ''' + @obj + ''' and [ObjID] = 0'
  3948.     end
  3949.     -- locked object is table
  3950.     else
  3951.     begin
  3952.         set @stmt = N'select [Process ID], [Lock Type], [Mode], [Status], [Owner], [Index], [Resource] from ' + @locktab + ' where [Object] = ''' + parsename(@obj,3) + '.' + parsename(@obj,2) + '.' + parsename(@obj,1) + ''''
  3953.     end
  3954. end
  3955. exec (@stmt)
  3956. return(0)
  3957. -- =============================================
  3958. -- end sp_MSget_current_activity
  3959. -- =============================================
  3960. go
  3961.  
  3962. raiserror(15339,-1,-1,'sp_MSset_current_activity')
  3963. go
  3964. -- =============================================
  3965. -- sp_MSset_current_activity
  3966. -- =============================================
  3967. create procedure dbo.sp_MSset_current_activity @id int OUTPUT
  3968. as
  3969.  
  3970. set transaction isolation level read uncommitted 
  3971. set quoted_identifier on
  3972. set nocount on
  3973. set lock_timeout 5000
  3974.  
  3975. declare @stmt as nvarchar(4000)
  3976. -- =============================================
  3977. -- make tables SPID depended
  3978. -- =============================================
  3979. declare @locktab as sysname
  3980. declare @proctab as sysname
  3981. declare @locktb2 as sysname
  3982. declare @proctb2 as sysname
  3983.  
  3984. set @id = @@spid
  3985. set @locktab = N'##lockinfo' + rtrim(convert(nvarchar(5), @id))
  3986. set @proctab = N'##procinfo' + rtrim(convert(nvarchar(5), @id))
  3987. set @locktb2 = N'tempdb..##lockinfo' + rtrim(convert(nvarchar(5), @id))
  3988. set @proctb2 = N'tempdb..##procinfo' + rtrim(convert(nvarchar(5), @id))
  3989.  
  3990. -- =============================================
  3991. -- delete temp tables
  3992. -- =============================================
  3993. if (object_id(@locktb2) is not null)
  3994.     exec(N'drop table ' + @locktab)
  3995.  
  3996. if (object_id(@proctb2) is not null)
  3997.     exec(N'drop table ' + @proctab)
  3998.  
  3999. -- =============================================
  4000. -- lockinfo table
  4001. -- =============================================
  4002. set @stmt = 
  4003. N'select [Process ID]    = l.req_spid,
  4004.          [DBID]          = l.rsc_dbid,
  4005.          [Database]      = db_name(l.rsc_dbid),
  4006.          [ObjID]         = l.rsc_objid,
  4007.          [Object]        = convert(nvarchar(386), ''''),
  4008.          [Table]     = convert(sysname, ''''),
  4009.          [ObjOwner]      = convert(sysname, ''''),
  4010.          [IdxID]         = l.rsc_indid,
  4011.          [Index]         = convert(sysname, ''''),
  4012.          [Lock Type]     = (select substring (v.name, 1, 4) from master.dbo.spt_values v where l.rsc_type = v.number and v.type = ''LR''),
  4013.          [Mode]          = (select substring (u.name, 1, 8) from master.dbo.spt_values u where l.req_mode + 1 = u.number and u.type = ''L''),
  4014.          [Status]        = (select substring (x.name, 1, 5) from master.dbo.spt_values x where l.req_status = x.number and x.type = ''LS''),
  4015.          [Owner]         = (select substring (o.name, 1, 8) from master.dbo.spt_values o where l.req_ownertype = o.number and o.type = ''LO''), 
  4016.          [Resource]      = substring (rsc_text, 1, 16)
  4017. into ' + @locktab + ' from master.dbo.syslockinfo l with (NOLOCK) order by l.req_spid'
  4018. exec (@stmt)
  4019.  
  4020. -- =============================================
  4021. -- processinfo table
  4022. -- =============================================
  4023. set @stmt =
  4024. N'select [Process ID]    = p.spid,
  4025.          [User]          = case when p.spid > 6
  4026.                               then convert(sysname, ISNULL(suser_sname(p.sid), rtrim(p.nt_domain) + ''\'' + rtrim(p.nt_username)))
  4027.                               else ''system''
  4028.                            end,
  4029.          [Database]      = case when p.dbid = 0
  4030.                               then ''no database context''
  4031.                               else db_name(p.dbid)
  4032.                            end,
  4033.          [Status]        = p.status,
  4034.          [Open Transactions] = p.open_tran,
  4035.          [Command]       = p.cmd,
  4036.          [Application]   = p.program_name,
  4037.          [Wait Time]     = p.waittime,
  4038.          [Wait Type]     = case when p.waittype = 0
  4039.                               then ''not waiting''
  4040.                               else p.lastwaittype
  4041.                            end,
  4042.          [Wait Resource] = case when p.waittype = 0
  4043.                               then ''''
  4044.                               else p.waitresource
  4045.                            end,
  4046.          [CPU]           = p.cpu,
  4047.          [Physical IO]   = p.physical_io,
  4048.          [Memory Usage]  = p.memusage,
  4049.          [Login Time]    = p.login_time,
  4050.          [Last Batch]    = p.last_batch,
  4051.          [Host]          = p.hostname,
  4052.          [Net Library]   = p.net_library,
  4053.          [Net Address]   = p.net_address,
  4054.          [Blocked By]     = p.blocked,
  4055.          [Blocking]      = 0
  4056. into ' + @proctab + ' from master.dbo.sysprocesses p with (NOLOCK) order by p.spid'
  4057. exec (@stmt)
  4058.  
  4059. -- =============================================
  4060. -- create temporary indexes
  4061. -- =============================================
  4062. set @stmt = N'create index ' + @locktab + '_spid on ' + @locktab + '([Process ID])'
  4063. exec (@stmt)
  4064.  
  4065. set @stmt = N'create index ' + @locktab + '_object on ' + @locktab + '([Object])'
  4066. exec (@stmt)
  4067.  
  4068. set @stmt = N'create unique index ' + @proctab + '_spid on ' + @proctab + '([Process ID])'
  4069. exec (@stmt)
  4070.  
  4071. set @stmt = N'create index ' + @proctab + '_blockedby on ' + @proctab + '([Blocked By])'
  4072. exec (@stmt)
  4073.  
  4074. set transaction isolation level read committed 
  4075.  
  4076. -- =============================================
  4077. -- replace placeholders get object names
  4078. -- =============================================
  4079. declare @lckdb sysname
  4080. declare @lckobjid integer
  4081. declare @lckobj sysname
  4082. declare @lckindid smallint
  4083. declare @lckind sysname
  4084.  
  4085. set @stmt = 'declare c1 cursor for select distinct [Database], [ObjID], [IdxID] from ' + @locktab + ' where [DBID] > 0 FOR READ ONLY'
  4086. exec (@stmt)
  4087.  
  4088. open  c1
  4089. fetch c1 into @lckdb, @lckobjid, @lckindid
  4090.  
  4091. while @@fetch_status >= 0
  4092. begin
  4093.     if (@lckobjid > 0)
  4094.     begin
  4095.     select @stmt ='update ' + @locktab + ' set [Table] = name, [ObjOwner] = user_name(uid) from ' + quotename(@lckdb, '[') + '.[dbo].[sysobjects] where id = ' + convert(nvarchar(10), @lckobjid) + ' and [Database] = ''' + @lckdb + ''' and [ObjID] = ' + convert(nvarchar(10), @lckobjid)
  4096.         exec (@stmt)
  4097.     select @stmt ='update ' + @locktab + ' set [Index] = name from ' + quotename(@lckdb, '[') + '.[dbo].[sysindexes] where id = ' + convert(nvarchar(10), @lckobjid)  + ' and indid = ' + convert(nvarchar(10), @lckindid) + ' and [Database] = ''' + @lckdb + ''' and [IdxID] = ' + convert(nvarchar(10), @lckindid)
  4098.         exec (@stmt)
  4099.     end
  4100.     fetch c1 into @lckdb, @lckobjid, @lckindid
  4101. end
  4102. deallocate c1
  4103.  
  4104. set @stmt = 'update ' + @locktab + ' set [Object] = [Database] where [ObjID] = 0'
  4105. exec (@stmt)
  4106.  
  4107. set @stmt = 'update ' + @locktab + ' set [Object] = rtrim([Database]) + ''.'' + rtrim([ObjOwner]) + ''.'' + rtrim([Table]) where [ObjID] > 0'
  4108. exec (@stmt)
  4109.  
  4110. -- =============================================
  4111. -- blocking
  4112. -- =============================================
  4113. set @stmt = 'update ' + @proctab + ' set [Blocking] = 1 where [Process ID] in (select [Blocked By] from ' + @proctab + ' where [Blocked By] > 0)'
  4114. exec (@stmt)
  4115.  
  4116. select [spid] = @id
  4117.  
  4118. return(0)
  4119. -- =============================================
  4120. -- end sp_MSset_current_activity
  4121. -- =============================================
  4122. go
  4123.  
  4124. raiserror(15339,-1,-1,'sp_configure')
  4125. go
  4126. CREATE PROCEDURE sp_configure  --- 1996/08/14 09:43
  4127.  
  4128.     @configname   varchar(35) = NULL   -- option name to configure
  4129.    ,@configvalue  int         = NULL   -- new configuration value
  4130. as
  4131.  
  4132. set nocount on
  4133.  
  4134. declare
  4135.     @confignum                int   --Num of the opt to be configured
  4136.    ,@configcount              int   --Num of options like @configname
  4137. -- ,@value_in_sysconfigures   int   --For one option, its value bef Upd
  4138.    ,@show_advance             int   --Y/N Read&Write actions on "advanced" opts
  4139.  
  4140. /*
  4141. **  Determine @maxnumber based on advance option in syscurconfigs.
  4142. */
  4143. if (select value from master.dbo.syscurconfigs where config = 518) = 1
  4144.    select @show_advance = 1   -- Display advanced options
  4145. else
  4146.    select @show_advance = 0   -- Don't display advanced options
  4147.  
  4148. /*
  4149. **  Make certain that max user info. reflects any addpak upgrades.
  4150. */
  4151. if (select high from master.dbo.spt_values where number=103 and type='C')
  4152.    <> @@max_connections
  4153.  
  4154.    update master.dbo.spt_values
  4155.       set high = @@max_connections
  4156.       where number = 103
  4157.          and type='C'
  4158.  
  4159. /*
  4160. **  If no option name is given, the procedure will just print out all the
  4161. **  options and their values.
  4162. */
  4163. if @configname is NULL
  4164.    begin
  4165.       select name, minimum = low, maximum = high,
  4166.          config_value = c.value,
  4167.          run_value = master.dbo.syscurconfigs.value
  4168.       from master.dbo.spt_values, master.dbo.sysconfigures c, master.dbo.syscurconfigs
  4169.       where type = 'C'
  4170.          and number = c.config
  4171.          and number = master.dbo.syscurconfigs.config
  4172.  
  4173.          and
  4174.              ((c.status & 2 <> 0 and @show_advance = 1)
  4175.                   OR
  4176.               (c.status & 2  = 0)
  4177.              )
  4178.       order by lower(name)
  4179.  
  4180.       return (0)
  4181.    end
  4182.  
  4183. /*
  4184. **  Use @configname and try to find the right option.
  4185. **  If there isn't just one, print appropriate diagnostics and return.
  4186. */
  4187. select @configcount = count(*)
  4188.    from master.dbo.spt_values v ,master.dbo.sysconfigures c
  4189.    where v.name like '%' + @configname + '%' and v.type = 'C'
  4190.       and v.number = c.config
  4191.       and
  4192.             ((c.status & 2 <> 0 and @show_advance = 1)
  4193.                   OR
  4194.              (c.status & 2  = 0)
  4195.             )
  4196.  
  4197. /*
  4198. **  If no option, show the user what the options are.
  4199. */
  4200. if @configcount = 0
  4201.    begin
  4202.       raiserror (15123,-1,-1,@configname)
  4203.  
  4204.       print ' '
  4205.       raiserror (15456,-1,-1)
  4206.  
  4207.       /*
  4208.       ** Show the user what the options are.
  4209.       */
  4210.       select name, minimum = low, maximum = high,
  4211.          config_value = c.value,
  4212.          run_value = master.dbo.syscurconfigs.value
  4213.       from master.dbo.spt_values, master.dbo.sysconfigures c, master.dbo.syscurconfigs
  4214.       where type = 'C'
  4215.          and number = c.config
  4216.          and number = master.dbo.syscurconfigs.config
  4217.  
  4218.          and
  4219.              ((c.status & 2 <> 0 and @show_advance = 1)
  4220.                    OR
  4221.               (c.status & 2  = 0)
  4222.              )
  4223.  
  4224.       return (1)
  4225.    end
  4226.  
  4227. /*
  4228. **  If more than one option like @configname, show the duplicates and return.
  4229. */
  4230. if @configcount > 1
  4231.    begin
  4232.       raiserror (15124,-1,-1,@configname)
  4233.       print ' '
  4234.  
  4235.       select duplicate_options = name
  4236.       from master.dbo.spt_values,master.dbo.sysconfigures c
  4237.       where name like '%' + @configname + '%'
  4238.          and type = 'C'
  4239.          and number = c.config
  4240.          and
  4241.              ((c.status & 2 <> 0 and @show_advance = 1)
  4242.                    OR
  4243.               (c.status & 2  = 0)
  4244.              )
  4245.  
  4246.       return (1)
  4247.    end
  4248. else
  4249.    /* There must be exactly one, so get the full name. */
  4250.    select @configname = name --,@value_in_sysconfigures = c.value
  4251.       from master.dbo.spt_values,master.dbo.sysconfigures c
  4252.       where name like '%' + @configname + '%' and type = 'C'
  4253.          and number = c.config
  4254.          and
  4255.              ((c.status & 2 <> 0 and @show_advance = 1)
  4256.                    OR
  4257.               (c.status & 2  = 0)
  4258.              )
  4259.  
  4260. /*
  4261. ** If @configvalue is NULL, just show the current state of the option.
  4262. */
  4263. if @configvalue is null
  4264. begin
  4265.  
  4266.    select       v.name
  4267.                ,v.low   as 'minimum'
  4268.                ,v.high  as 'maximum'
  4269.                ,c.value as 'config_value'
  4270.                ,u.value as 'run_value'
  4271.          from
  4272.                 master.dbo.spt_values     v  left outer join
  4273.                 master.dbo.sysconfigures  c  on v.number = c.config
  4274.                                              left outer join
  4275.                 master.dbo.syscurconfigs  u  on v.number = u.config
  4276.          where
  4277.                 v.type = 'C  '
  4278.          and    v.name like '%' + @configname + '%'
  4279.          and
  4280.                ((c.status & 2 <> 0 and @show_advance = 1)
  4281.                      OR
  4282.                 (c.status & 2  = 0)
  4283.                )
  4284.  
  4285.    return (0)
  4286. end
  4287.  
  4288. /*
  4289. **  Only the SA can execute the update part of this procedure so check.
  4290. */
  4291. if (not is_srvrolemember('serveradmin') = 1)
  4292.    begin
  4293.       raiserror(15125,-1,-1)
  4294.       return (1)
  4295.    end
  4296.  
  4297. /*
  4298. **  Now get the configuration number.
  4299. */
  4300. select @confignum = number
  4301.    from master.dbo.spt_values,master.dbo.sysconfigures c
  4302.    where type = 'C'
  4303.       and (@configvalue between low and high or @configvalue = 0)
  4304.       and name like '%' + @configname + '%'
  4305.       and number = c.config
  4306.       and
  4307.             ((c.status & 2 <> 0 and @show_advance = 1)
  4308.                   OR
  4309.              (c.status & 2  = 0)
  4310.             )
  4311.  
  4312. /*
  4313. **  If this is the number of default language, we want to make sure
  4314. **  that the new value is a valid language id in Syslanguages.
  4315. */
  4316. if @confignum = 124
  4317.    begin
  4318.    if not exists (select * from master.dbo.syslanguages
  4319.          where langid = @configvalue)
  4320.       begin
  4321.          /* 0 is default language, us_english */
  4322.          if @configvalue <> 0
  4323.             begin
  4324.                raiserror(15127,-1,-1)
  4325.                return (1)
  4326.             end
  4327.       end
  4328.    end
  4329.  
  4330. /*
  4331. **  If this is the number of kernel language, we want to make sure
  4332. **  that the new value is a valid language id in Syslanguages.
  4333. */
  4334. if @confignum = 132
  4335.    begin
  4336.    if not exists (select * from master.dbo.syslanguages
  4337.          where langid = @configvalue)
  4338.       begin
  4339.          /* 0 is default language, us_english */
  4340.          if @configvalue <> 0
  4341.             begin
  4342.                raiserror(15028,-1,-1)
  4343.                return (1)
  4344.             end
  4345.       end
  4346.    end
  4347.  
  4348. /*
  4349. **  "user options" should not try to set incompatible options/values.
  4350. */
  4351. if @confignum = 1534  --"user options"
  4352.    begin
  4353.  
  4354.    if (@configvalue & (1024+2048) = (1024+2048)) --ansi_null_default_on/off
  4355.       begin
  4356.       raiserror(15303,-1,-1,@configvalue)
  4357.       return (1)
  4358.       end
  4359.    end
  4360.  
  4361. /*
  4362. **  Although the @configname is good, @configvalue wasn't in range.
  4363. */
  4364. if @confignum is NULL
  4365.    begin
  4366.    raiserror(15129,-1,-1,@configvalue,@configname)
  4367.    return (1)
  4368.    end
  4369.  
  4370. --Msg 15002, but in 6.5 allow this inside a txn (not check @@trancount) #12828.
  4371.  
  4372. /*
  4373. **  Now update sysconfigures.
  4374. */
  4375. update master.dbo.sysconfigures set value = @configvalue
  4376.    where config = @confignum
  4377.  
  4378. /*
  4379. ** Flush the procedure cache - this is to account for options which become
  4380. ** effective immediately (ie. dont need a server restart).
  4381. */
  4382. dbcc freeproccache
  4383.  
  4384. raiserror(15457,-1,-1)
  4385.  
  4386. return (0) -- sp_configure
  4387. go
  4388.  
  4389.  
  4390. checkpoint
  4391. go
  4392.  
  4393.  
  4394.  
  4395. raiserror(15339,-1,-1,'sp_dbremove')
  4396. go
  4397. create procedure sp_dbremove --- 1996/04/08 00:00
  4398. @dbname sysname = null,
  4399. @dropdev varchar(10) = null
  4400. as
  4401.     declare @dbid int
  4402.     declare @devname sysname
  4403.     declare @physname varchar(255)
  4404.  
  4405.     if @dbname is null
  4406.         begin
  4407.             raiserror(15131,-1,-1)
  4408.             return(1)
  4409.         end
  4410.  
  4411.     if lower(@dropdev) <> 'dropdev' and @dropdev is not null
  4412.         begin
  4413.             raiserror(15131,-1,-1)
  4414.             return(1)
  4415.         end
  4416.  
  4417.     /* Check to see if database exists. */
  4418.     select @dbid = null
  4419.     select @dbid = dbid from master.dbo.sysdatabases where name=@dbname
  4420.     if @dbid is null
  4421.         begin
  4422.             raiserror(15010,-1,-1,@dbname)
  4423.             return(1)
  4424.         end
  4425.  
  4426.     /* Make sure no one is in the db. */
  4427.     if (select count(*) from master.dbo.sysprocesses where dbid = @dbid) > 0
  4428.         begin
  4429.             raiserror(15069,-1,-1)
  4430.             return (1)
  4431.         end
  4432.  
  4433.     update master.dbo.sysdatabases set status = 256 where dbid=@dbid
  4434.     dbcc dbrepair(@dbname,dropdb,noinit)
  4435.     raiserror(15458,-1,-1)
  4436.  
  4437.     return(0)
  4438. -- sp_dbremove
  4439. go
  4440.  
  4441.  
  4442.  
  4443.  
  4444. raiserror(15339,-1,-1,'sp_create_removable')
  4445. go
  4446. create procedure sp_create_removable
  4447.  
  4448. @dbname        sysname = null,    /* name of db */
  4449. @syslogical    sysname = null,    /* logical name of system device */
  4450. @sysphysical    nvarchar (260) = null,    /* physical name of system device */
  4451. @syssize    int = null,        /* size of sys device in Meg. */
  4452. @loglogical    sysname = null,    /* logical name of log device */
  4453. @logphysical    nvarchar (260) = null,    /* physical name of log device */
  4454. @logsize    int = null,        /* size of log device in Meg. */
  4455. @datalogical1    sysname = null,    /* logical name of data device */
  4456. @dataphysical1    nvarchar (260) = null,    /* physical name of data device */
  4457. @datasize1    int = null,        /* size of data device in Meg. */
  4458. @datalogical2    sysname = null,    /* logical name of data device */
  4459. @dataphysical2    nvarchar (260) = null,    /* physical name of data device */
  4460. @datasize2    int = null,        /* size of data device in Meg. */
  4461. @datalogical3    sysname = null,    /* logical name of data device */
  4462. @dataphysical3    nvarchar (260) = null,    /* physical name of data device */
  4463. @datasize3    int = null,        /* size of data device in Meg. */
  4464. @datalogical4    sysname = null,    /* logical name of data device */
  4465. @dataphysical4    nvarchar (260) = null,    /* physical name of data device */
  4466. @datasize4    int = null,        /* size of data device in Meg. */
  4467. @datalogical5    sysname = null,    /* logical name of data device */
  4468. @dataphysical5    nvarchar (260) = null,    /* physical name of data device */
  4469. @datasize5    int = null,        /* size of data device in Meg. */
  4470. @datalogical6    sysname = null,    /* logical name of data device */
  4471. @dataphysical6    nvarchar (260) = null,    /* physical name of data device */
  4472. @datasize6    int = null,        /* size of data device in Meg. */
  4473. @datalogical7    sysname = null,    /* logical name of data device */
  4474. @dataphysical7    nvarchar (260) = null,    /* physical name of data device */
  4475. @datasize7    int = null,        /* size of data device in Meg. */
  4476. @datalogical8    sysname = null,    /* logical name of data device */
  4477. @dataphysical8    nvarchar (260) = null,    /* physical name of data device */
  4478. @datasize8    int = null,        /* size of data device in Meg. */
  4479. @datalogical9    sysname = null,    /* logical name of data device */
  4480. @dataphysical9    nvarchar (260) = null,    /* physical name of data device */
  4481. @datasize9    int = null,        /* size of data device in Meg. */
  4482. @datalogical10    sysname = null,    /* logical name of data device */
  4483. @dataphysical10    nvarchar (260) = null,    /* physical name of data device */
  4484. @datasize10    int = null,        /* size of data device in Meg. */
  4485. @datalogical11    sysname = null,    /* logical name of data device */
  4486. @dataphysical11    nvarchar (260) = null,    /* physical name of data device */
  4487. @datasize11    int = null,        /* size of data device in Meg. */
  4488. @datalogical12    sysname = null,    /* logical name of data device */
  4489. @dataphysical12    nvarchar (260) = null,    /* physical name of data device */
  4490. @datasize12    int = null,        /* size of data device in Meg. */
  4491. @datalogical13    sysname = null,    /* logical name of data device */
  4492. @dataphysical13    nvarchar (260) = null,    /* physical name of data device */
  4493. @datasize13    int = null,        /* size of data device in Meg. */
  4494. @datalogical14    sysname = null,    /* logical name of data device */
  4495. @dataphysical14    nvarchar (260) = null,    /* physical name of data device */
  4496. @datasize14    int = null,        /* size of data device in Meg. */
  4497. @datalogical15    sysname = null,    /* logical name of data device */
  4498. @dataphysical15    nvarchar (260) = null,    /* physical name of data device */
  4499. @datasize15    int = null,        /* size of data device in Meg. */
  4500. @datalogical16    sysname = null,    /* logical name of data device */
  4501. @dataphysical16 nvarchar (260) = null,    /* physical name of data device */
  4502. @datasize16    int = null        /* size of data device in Meg. */
  4503.     
  4504. as
  4505.  
  4506. declare @retcode int,
  4507.     @exec_str nvarchar (460),
  4508.     @numdevs int
  4509.  
  4510. if suser_id() <> 1    -- Make sure that it's the SA executing this.
  4511.     begin
  4512.         raiserror(15003,-1,-1, 'sysadmin')
  4513.         return(1)    
  4514.     end
  4515.  
  4516. if @dbname is null
  4517.     or @syslogical is null
  4518.     or @sysphysical is null
  4519.     or @syssize is null
  4520.     or @loglogical is null
  4521.     or @logphysical is null
  4522.     or @logsize is null
  4523.     or @datalogical1 is null
  4524.     or @dataphysical1 is null
  4525.     or @datasize1 is null
  4526.         begin
  4527.             raiserror (15261,-1,-1)
  4528.             return (1)
  4529.         end
  4530.  
  4531. if exists (select * from sysdatabases where name = @dbname)
  4532.     begin
  4533.         raiserror(15032,-1,-1,@dbname)
  4534.         return(1)
  4535.     end
  4536.  
  4537. /* Check to verify that valid sizes were supplied for required devices. */
  4538. if @syssize < 1 or @logsize < 1 or @datasize1 < 1
  4539.     begin
  4540.         raiserror (15262,-1,-1)
  4541.         return(1)
  4542.     end
  4543.  
  4544. /* Check to see if a valid database name was supplied. */
  4545. exec @retcode = sp_validname @dbname
  4546. if @retcode <> 0
  4547.     return(1)
  4548.  
  4549. /* valid syslogical? */
  4550. exec @retcode = sp_validname @syslogical
  4551. if @retcode <> 0
  4552.     return(1)
  4553.  
  4554. /* valid loglogical? */
  4555. exec @retcode = sp_validname @loglogical
  4556. if @retcode <> 0
  4557.     return(1)
  4558.  
  4559. /* valid datalogical1? */
  4560. exec @retcode = sp_validname @datalogical1
  4561. if @retcode <> 0
  4562.     return(1)
  4563.  
  4564.  
  4565. /* Create the database's system device segment. */
  4566. select @exec_str = 'CREATE DATABASE '
  4567.         + quotename( @dbname , '[') 
  4568.         + ' ON (NAME ='
  4569.         + quotename( @syslogical , '[') 
  4570.         + ',FILENAME ='
  4571.         + ''''
  4572.         + @sysphysical
  4573.         + ''''
  4574.         + ',SIZE ='
  4575.         + convert(varchar(28),@syssize)
  4576.         + ') LOG ON (NAME='
  4577.         + quotename( @loglogical , '[') 
  4578.         + ',FILENAME ='
  4579.         + ''''
  4580.         + @logphysical
  4581.         + ''''
  4582.         + ',SIZE ='
  4583.         + convert(varchar(28),@logsize)
  4584.         + ')'
  4585. exec(@exec_str)
  4586.  
  4587. if @@error <> 0
  4588.     begin
  4589.         raiserror(15264,-1,-1,'system or log')
  4590.         return(1)
  4591.     end
  4592.  
  4593. -- Add a filegroup for data
  4594. select @exec_str = 'ALTER DATABASE '
  4595.         + quotename( @dbname , '[') 
  4596.         + ' ADD FILEGROUP readonlyfilegroup'
  4597.  
  4598. exec(@exec_str)
  4599.  
  4600. if @@error <> 0
  4601.     begin
  4602.         raiserror(15264,-1,-1,'user filegroup')
  4603.         return(1)
  4604.     end
  4605.  
  4606. select @exec_str = 'ALTER DATABASE '
  4607.         + quotename( @dbname , '[') 
  4608.         +' ADD FILE (NAME ='
  4609.         + quotename( @datalogical1 , '[') 
  4610.         + ',FILENAME ='
  4611.         + ''''
  4612.         + @dataphysical1
  4613.         + ''''
  4614.         + ',SIZE ='
  4615.         + convert(varchar(28),@datasize1)
  4616.         + ') TO FILEGROUP readonlyfilegroup'
  4617.         exec(@exec_str)
  4618.  
  4619. if @@error <> 0
  4620.     begin
  4621.         raiserror(15264,-1,-1,'user data')
  4622.         exec ('drop database '+ @dbname)
  4623.         return(1)
  4624.     end
  4625.  
  4626. -- Make this the default filegroup
  4627. select @exec_str = 'ALTER DATABASE '
  4628.         + quotename( @dbname , '[') 
  4629.         + ' MODIFY FILEGROUP readonlyfilegroup DEFAULT'
  4630.  
  4631. exec(@exec_str)
  4632.  
  4633. if @@error <> 0
  4634.     begin
  4635.         raiserror(15264,-1,-1,'default filegroup')
  4636.         return(1)
  4637.     end
  4638.  
  4639.  
  4640. /* Check out optional data devices. */
  4641.  
  4642. if @datalogical2 is not null
  4643. begin
  4644.     select @exec_str = 'ALTER DATABASE '
  4645.         + quotename( @dbname , '[') 
  4646.         +' ADD FILE (NAME ='
  4647.         + quotename( @datalogical2 , '[') 
  4648.         + ',FILENAME ='
  4649.         + ''''
  4650.         + @dataphysical2
  4651.         + ''''
  4652.         + ',SIZE ='
  4653.         + convert(varchar(28),@datasize2)
  4654.         + ') TO FILEGROUP readonlyfilegroup'
  4655.     exec(@exec_str)
  4656.     if @retcode <> 0
  4657.     begin
  4658.         raiserror(15269,-1,-1,@datalogical2)
  4659.         exec ('drop database '+ @dbname)
  4660.         return(1)
  4661.     end
  4662.     select @numdevs = 2
  4663. end
  4664. else goto no_more_devs
  4665.  
  4666. if @datalogical3 is not null
  4667. begin
  4668.     select @exec_str = 'ALTER DATABASE '
  4669.         + quotename( @dbname , '[') 
  4670.         +' ADD FILE (NAME ='
  4671.         + quotename( @datalogical3 , '[') 
  4672.         + ',FILENAME ='
  4673.         + ''''
  4674.         + @dataphysical3
  4675.         + ''''
  4676.         + ',SIZE ='
  4677.         + convert(varchar(28),@datasize3)
  4678.         + ') TO FILEGROUP readonlyfilegroup'
  4679.     exec(@exec_str)
  4680.     if @retcode <> 0
  4681.     begin
  4682.         raiserror(15269,-1,-1,@datalogical3)
  4683.         exec ('drop database '+ @dbname)
  4684.         return(1)
  4685.     end
  4686.     select @numdevs = 3
  4687. end
  4688. else goto no_more_devs
  4689.  
  4690. if @datalogical4 is not null
  4691. begin
  4692.     select @exec_str = 'ALTER DATABASE '
  4693.         + quotename( @dbname , '[') 
  4694.         +' ADD FILE (NAME ='
  4695.         + quotename( @datalogical4 , '[') 
  4696.         + ',FILENAME ='
  4697.         + ''''
  4698.         + @dataphysical4
  4699.         + ''''
  4700.         + ',SIZE ='
  4701.         + convert(varchar(28),@datasize4)
  4702.         + ') TO FILEGROUP readonlyfilegroup'
  4703.     exec(@exec_str)
  4704.     if @retcode <> 0
  4705.     begin
  4706.         raiserror(15269,-1,-1,@datalogical4)
  4707.         exec ('drop database '+ @dbname)
  4708.         return(1)
  4709.     end
  4710.     select @numdevs = 4
  4711. end
  4712. else goto no_more_devs
  4713.  
  4714. if @datalogical5 is not null
  4715. begin
  4716.     select @exec_str = 'ALTER DATABASE '
  4717.         + quotename( @dbname , '[') 
  4718.         +' ADD FILE (NAME ='
  4719.         + quotename( @datalogical5 , '[') 
  4720.         + ',FILENAME ='
  4721.         + ''''
  4722.         + @dataphysical5
  4723.         + ''''
  4724.         + ',SIZE ='
  4725.         + convert(varchar(28),@datasize5)
  4726.         + ') TO FILEGROUP readonlyfilegroup'
  4727.     exec(@exec_str)
  4728.     if @retcode <> 0
  4729.     begin
  4730.         raiserror(15269,-1,-1,@datalogical5)
  4731.         exec ('drop database '+ @dbname)
  4732.         return(1)
  4733.     end
  4734.     select @numdevs = 5
  4735. end
  4736. else goto no_more_devs
  4737.  
  4738. if @datalogical6 is not null
  4739. begin
  4740.     select @exec_str = 'ALTER DATABASE '
  4741.         + quotename( @dbname , '[') 
  4742.         +' ADD FILE (NAME ='
  4743.         + quotename( @datalogical6 , '[') 
  4744.         + ',FILENAME ='
  4745.         + ''''
  4746.         + @dataphysical6
  4747.         + ''''
  4748.         + ',SIZE ='
  4749.         + convert(varchar(28),@datasize6)
  4750.         + ') TO FILEGROUP readonlyfilegroup'
  4751.     exec(@exec_str)
  4752.     if @retcode <> 0
  4753.     begin
  4754.         raiserror(15269,-1,-1,@datalogical6)
  4755.         exec ('drop database '+ @dbname)
  4756.         return(1)
  4757.     end
  4758.     select @numdevs = 6
  4759. end
  4760. else goto no_more_devs
  4761.  
  4762. if @datalogical7 is not null
  4763. begin
  4764.     select @exec_str = 'ALTER DATABASE '
  4765.         + quotename( @dbname , '[') 
  4766.         +' ADD FILE (NAME ='
  4767.         + quotename( @datalogical7 , '[') 
  4768.         + ',FILENAME ='
  4769.         + ''''
  4770.         + @dataphysical7
  4771.         + ''''
  4772.         + ',SIZE ='
  4773.         + convert(varchar(28),@datasize7)
  4774.         + ') TO FILEGROUP readonlyfilegroup'
  4775.     exec(@exec_str)
  4776.     if @retcode <> 0
  4777.     begin
  4778.         raiserror(15269,-1,-1,@datalogical7)
  4779.         exec ('drop database '+ @dbname)
  4780.         return(1)
  4781.     end
  4782.     select @numdevs = 7
  4783. end
  4784. else goto no_more_devs
  4785.  
  4786. if @datalogical8 is not null
  4787. begin
  4788.     select @exec_str = 'ALTER DATABASE '
  4789.         + quotename( @dbname , '[') 
  4790.         +' ADD FILE (NAME ='
  4791.         + quotename( @datalogical8 , '[') 
  4792.         + ',FILENAME ='
  4793.         + ''''
  4794.         + @dataphysical8
  4795.         + ''''
  4796.         + ',SIZE ='
  4797.         + convert(varchar(28),@datasize8)
  4798.         + ') TO FILEGROUP readonlyfilegroup'
  4799.     exec(@exec_str)
  4800.     if @retcode <> 0
  4801.     begin
  4802.         raiserror(15269,-1,-1,@datalogical8)
  4803.         exec ('drop database '+ @dbname)
  4804.         return(1)
  4805.     end
  4806.     select @numdevs = 8
  4807. end
  4808. else goto no_more_devs
  4809. if @datalogical9 is not null
  4810. begin
  4811.     select @exec_str = 'ALTER DATABASE '
  4812.         + quotename( @dbname , '[') 
  4813.         +' ADD FILE (NAME ='
  4814.         + quotename( @datalogical9 , '[') 
  4815.         + ',FILENAME ='
  4816.         + ''''
  4817.         + @dataphysical9
  4818.         + ''''
  4819.         + ',SIZE ='
  4820.         + convert(varchar(28),@datasize9)
  4821.         + ') TO FILEGROUP readonlyfilegroup'
  4822.     exec(@exec_str)
  4823.     if @retcode <> 0
  4824.     begin
  4825.         raiserror(15269,-1,-1,@datalogical9)
  4826.         exec ('drop database '+ @dbname)
  4827.         return(1)
  4828.     end
  4829.     select @numdevs = 9
  4830. end
  4831. else goto no_more_devs
  4832.  
  4833. if @datalogical10 is not null
  4834. begin
  4835.     select @exec_str = 'ALTER DATABASE '
  4836.         + quotename( @dbname , '[') 
  4837.         +' ADD FILE (NAME ='
  4838.         + quotename( @datalogical10 , '[') 
  4839.         + ',FILENAME ='
  4840.         + ''''
  4841.         + @dataphysical10
  4842.         + ''''
  4843.         + ',SIZE ='
  4844.         + convert(varchar(28),@datasize10)
  4845.         + ') TO FILEGROUP readonlyfilegroup'
  4846.     exec(@exec_str)
  4847.     if @retcode <> 0
  4848.     begin
  4849.         raiserror(15269,-1,-1,@datalogical10)
  4850.         exec ('drop database '+ @dbname)
  4851.         return(1)
  4852.     end
  4853.     select @numdevs = 10
  4854. end
  4855. else goto no_more_devs
  4856.  
  4857. if @datalogical11 is not null
  4858. begin
  4859.     select @exec_str = 'ALTER DATABASE '
  4860.         + quotename( @dbname , '[') 
  4861.         +' ADD FILE (NAME ='
  4862.         + quotename( @datalogical11 , '[') 
  4863.         + ',FILENAME ='
  4864.         + ''''
  4865.         + @dataphysical11
  4866.         + ''''
  4867.         + ',SIZE ='
  4868.         + convert(varchar(28),@datasize11)
  4869.         + ') TO FILEGROUP readonlyfilegroup'
  4870.     exec(@exec_str)
  4871.     if @retcode <> 0
  4872.     begin
  4873.         raiserror(15269,-1,-1,@datalogical11)
  4874.         exec ('drop database '+ @dbname)
  4875.         return(1)
  4876.     end
  4877.     select @numdevs = 11
  4878. end
  4879. else goto no_more_devs
  4880.  
  4881. if @datalogical12 is not null
  4882. begin
  4883.     select @exec_str = 'ALTER DATABASE '
  4884.         + quotename( @dbname , '[') 
  4885.         +' ADD FILE (NAME ='
  4886.         + quotename( @datalogical12 , '[') 
  4887.         + ',FILENAME ='
  4888.         + ''''
  4889.         + @dataphysical12
  4890.         + ''''
  4891.         + ',SIZE ='
  4892.         + convert(varchar(28),@datasize12)
  4893.         + ') TO FILEGROUP readonlyfilegroup'
  4894.     exec(@exec_str)
  4895.     if @retcode <> 0
  4896.     begin
  4897.         raiserror(15269,-1,-1,@datalogical12)
  4898.         exec ('drop database '+ @dbname)
  4899.         return(1)
  4900.     end
  4901.     select @numdevs = 12
  4902. end
  4903. else goto no_more_devs
  4904.  
  4905. if @datalogical13 is not null
  4906. begin
  4907.     select @exec_str = 'ALTER DATABASE '
  4908.         + quotename( @dbname , '[') 
  4909.         +' ADD FILE (NAME ='
  4910.         + quotename( @datalogical13 , '[') 
  4911.         + ',FILENAME ='
  4912.         + ''''
  4913.         + @dataphysical13
  4914.         + ''''
  4915.         + ',SIZE ='
  4916.         + convert(varchar(28),@datasize13)
  4917.         + ') TO FILEGROUP readonlyfilegroup'
  4918.     exec(@exec_str)
  4919.     if @retcode <> 0
  4920.     begin
  4921.         raiserror(15269,-1,-1,@datalogical13)
  4922.         exec ('drop database '+ @dbname)
  4923.         return(1)
  4924.     end
  4925.     select @numdevs = 13
  4926. end
  4927. else goto no_more_devs
  4928.  
  4929. if @datalogical14 is not null
  4930. begin
  4931.     select @exec_str = 'ALTER DATABASE '
  4932.         + quotename( @dbname , '[') 
  4933.         +' ADD FILE (NAME ='
  4934.         + quotename( @datalogical14 , '[') 
  4935.         + ',FILENAME ='
  4936.         + ''''
  4937.         + @dataphysical14
  4938.         + ''''
  4939.         + ',SIZE ='
  4940.         + convert(varchar(28),@datasize14)
  4941.         + ') TO FILEGROUP readonlyfilegroup'
  4942.     exec(@exec_str)
  4943.     if @retcode <> 0
  4944.     begin
  4945.         raiserror(15269,-1,-1,@datalogical14)
  4946.         exec ('drop database '+ @dbname)
  4947.         return(1)
  4948.     end
  4949.     select @numdevs = 14
  4950. end
  4951. else goto no_more_devs
  4952.  
  4953. if @datalogical15 is not null
  4954. begin
  4955.     select @exec_str = 'ALTER DATABASE '
  4956.         + quotename( @dbname , '[') 
  4957.         +' ADD FILE (NAME ='
  4958.         + quotename( @datalogical15 , '[') 
  4959.         + ',FILENAME ='
  4960.         + ''''
  4961.         + @dataphysical15
  4962.         + ''''
  4963.         + ',SIZE ='
  4964.         + convert(varchar(28),@datasize15)
  4965.         + ') TO FILEGROUP readonlyfilegroup'
  4966.     exec(@exec_str)
  4967.     if @retcode <> 0
  4968.     begin
  4969.         raiserror(15269,-1,-1,@datalogical15)
  4970.         exec ('drop database '+ @dbname)
  4971.         return(1)
  4972.     end
  4973.     select @numdevs = 15
  4974. end
  4975. else goto no_more_devs
  4976.  
  4977. if @datalogical16 is not null
  4978. begin
  4979.     select @exec_str = 'ALTER DATABASE '
  4980.         + quotename( @dbname , '[') 
  4981.         +' ADD FILE (NAME ='
  4982.         + quotename( @datalogical16 , '[') 
  4983.         + ',FILENAME ='
  4984.         + ''''
  4985.         + @dataphysical16
  4986.         + ''''
  4987.         + ',SIZE ='
  4988.         + convert(varchar(28),@datasize16)
  4989.         + ') TO FILEGROUP readonlyfilegroup'
  4990.     exec(@exec_str)
  4991.     if @retcode <> 0
  4992.     begin
  4993.         raiserror(15269,-1,-1,@datalogical16)
  4994.         exec ('drop database '+ @dbname)
  4995.         return(1)
  4996.     end
  4997.     select @numdevs = 16
  4998. end
  4999.  
  5000. no_more_devs:
  5001.  
  5002.  
  5003. return(0) -- sp_create_removable
  5004. go
  5005.  
  5006.  
  5007.  
  5008. raiserror(15339,-1,-1,'sp_depends')
  5009. go
  5010. create procedure sp_depends  --- 1996/08/09 16:51
  5011. @objname nvarchar(776)        /* the object we want to check */
  5012. as
  5013.  
  5014. declare @objid int            /* the id of the object we want */
  5015. declare @found_some bit            /* flag for dependencies found */
  5016. declare @dbname sysname
  5017.  
  5018. /*
  5019. **  Make sure the @objname is local to the current database.
  5020. */
  5021.  
  5022. select @dbname = parsename(@objname,3) 
  5023.  
  5024. if @dbname is not null and @dbname <> db_name()
  5025.     begin
  5026.         raiserror(15250,-1,-1)
  5027.         return (1)
  5028.     end
  5029.  
  5030. /*
  5031. **  See if @objname exists.
  5032. */
  5033. select @objid = object_id(@objname)
  5034. if @objid is null
  5035.     begin
  5036.         select @dbname = db_name()
  5037.         raiserror(15009,-1,-1,@objname,@dbname)
  5038.         return (1)
  5039.     end
  5040.  
  5041. /*
  5042. **  Initialize @found_some to indicate that we haven't seen any dependencies.
  5043. */
  5044. select @found_some = 0
  5045.  
  5046. set nocount on
  5047.  
  5048. /*
  5049. **  Print out the particulars about the local dependencies.
  5050. */
  5051. if exists (select *
  5052.         from sysdepends
  5053.             where id = @objid)
  5054. begin
  5055.     raiserror(15459,-1,-1)
  5056.     select         'name' = substring((s6.name+ '.' + o1.name), 1, 40),
  5057.              type = substring(v2.name, 5, 16),
  5058.              updated = substring(u4.name, 1, 7),
  5059.              selected = substring(w5.name, 1, 8),
  5060.              'column' = col_name(d3.depid, d3.depnumber)
  5061.         from     sysobjects        o1
  5062.             ,master.dbo.spt_values    v2
  5063.             ,sysdepends        d3
  5064.             ,master.dbo.spt_values    u4
  5065.             ,master.dbo.spt_values    w5 --11667
  5066.             ,sysusers        s6
  5067.         where     o1.id = d3.depid
  5068.         and     o1.xtype = substring(v2.name,1,2) and v2.type = 'O9T'
  5069.         and     u4.type = 'B' and u4.number = d3.resultobj
  5070.         and     w5.type = 'B' and w5.number = d3.readobj|d3.selall
  5071.         and     d3.id = @objid
  5072.         and     o1.uid = s6.uid
  5073.  
  5074.     select @found_some = 1
  5075. end
  5076.  
  5077. /*
  5078. **  Now check for things that depend on the object.
  5079. */
  5080. if exists (select *
  5081.         from sysdepends
  5082.             where depid = @objid)
  5083. begin
  5084.         raiserror(15460,-1,-1)
  5085.     select distinct 'name' = substring((s.name + '.' + o.name), 1, 40),
  5086.         type = substring(v.name, 5, 16)
  5087.             from sysobjects o, master.dbo.spt_values v, sysdepends d,
  5088.                 sysusers s
  5089.             where o.id = d.id
  5090.                 and o.xtype = substring(v.name,1,2) and v.type = 'O9T'
  5091.                 and d.depid = @objid
  5092.                 and o.uid = s.uid
  5093.  
  5094.     select @found_some = 1
  5095. end
  5096.  
  5097. /*
  5098. **  Did we find anything in sysdepends?
  5099. */
  5100. if @found_some = 0
  5101.     raiserror(15461,-1,-1)
  5102.  
  5103. set nocount off
  5104.  
  5105. return (0) -- sp_depends
  5106. go
  5107.  
  5108. raiserror(15339,-1,-1,'sp_detach_db')
  5109. go
  5110. create procedure sp_detach_db
  5111. @dbname sysname = null,
  5112. @skipchecks nvarchar(10) = null
  5113. as
  5114. declare @dbid int
  5115. declare @exec_stmt nvarchar(540)
  5116.     if @dbname is null
  5117.         begin
  5118.             raiserror(15354,-1,-1)
  5119.             return(1)
  5120.         end
  5121.  
  5122.     if lower(@skipchecks) <> N'true' 
  5123.         and lower(@skipchecks) <> N'false' 
  5124.         and @skipchecks is not null
  5125.         begin
  5126.             raiserror(15354,-1,-1)
  5127.             return(1)
  5128.         end
  5129.  
  5130.     select @dbid = null
  5131.     select @dbid = dbid from master.dbo.sysdatabases where name=@dbname
  5132.     if @dbid is null
  5133.         begin
  5134.             raiserror(15010,-1,-1,@dbname)
  5135.             return(1)
  5136.         end
  5137.  
  5138.     -- make sure not trying to detach within a transaction
  5139.     if @@trancount > 0
  5140.         begin
  5141.             raiserror(226,-1,-1,'SP_DETACH_DB')
  5142.             return(1)
  5143.         end
  5144.  
  5145.     -- run UPDATE STATISTICS on all tables in the database so they are current
  5146.     -- when transferred to READONLY media
  5147.     if lower(@skipchecks) <> N'true' 
  5148.         begin
  5149.             print 'Running UPDATE STATISTICS on all tables'
  5150.             select @exec_stmt = 'USE ' + quotename( @dbname , '[') 
  5151.             + ' exec sp_updatestats ' 
  5152.             exec (@exec_stmt)
  5153.         end
  5154.  
  5155.     select @exec_stmt = 'DBCC DETACHDB (' 
  5156.             + quotename( @dbname , '[') 
  5157.             + ')'
  5158.     exec (@exec_stmt)
  5159.     return (0) -- sp_detach_db
  5160. go
  5161.  
  5162.  
  5163. raiserror(15339,-1,-1,'sp_diskdefault')
  5164. go
  5165. create procedure sp_diskdefault --- 1996/04/08 00:00
  5166. @logicalname    sysname,        /* logical name of the device */
  5167. @defstatus    varchar(15)        /* turn on or off */
  5168. as
  5169.  
  5170. /*
  5171. **  If we're in a transaction, disallow this since it might make recovery
  5172. **  impossible.
  5173. */
  5174. set implicit_transactions off
  5175. if @@trancount > 0
  5176.     begin
  5177.            raiserror(15002,-1,-1,'sp_diskdefault')
  5178.        return (1)
  5179.     end
  5180.  
  5181. /*
  5182. **  Only the SA can run this sproc.
  5183. */
  5184. if not is_srvrolemember('diskadmin') = 1
  5185.     begin
  5186.         raiserror(15003,-1,-1, 'diskadmin')
  5187.         return (1)
  5188.     end
  5189.  
  5190. /*
  5191. **  Make sure that a device with @logicalname exists.
  5192. */
  5193. if not exists (select * from master.dbo.sysdevices where name = @logicalname)
  5194.     begin
  5195.         raiserror(15012,-1,-1,@logicalname)
  5196.         return (1)
  5197.     end
  5198.  
  5199. /*
  5200. **  Make sure that it is a database disk and not a dump device.
  5201. */
  5202. if exists (select * from master.dbo.sysdevices
  5203.         where name = @logicalname
  5204.             and status & 16 = 16)
  5205.     begin
  5206.         raiserror(15035,-1,-1,@logicalname)
  5207.         return (1)
  5208.     end
  5209.  
  5210. /*
  5211. **  Make sure that the database disk is NOT a RAM device.
  5212. */
  5213. if exists (select *
  5214.         from master.dbo.sysdevices
  5215.         where name = @logicalname
  5216.             and status & 2048 = 2048 )
  5217.     begin
  5218.         raiserror(15139,-1,-1)
  5219.         return (1)
  5220.     end
  5221.  
  5222. if @defstatus = 'defaulton'
  5223.     begin
  5224.         update master.dbo.sysdevices set status = status | 1
  5225.             where name = @logicalname
  5226.         return (0)
  5227.     end
  5228.  
  5229. if @defstatus = 'defaultoff'
  5230.     begin
  5231.         update master.dbo.sysdevices set status = status & ~1
  5232.             where name = @logicalname
  5233.         return (0)
  5234.     end
  5235.  
  5236. /*
  5237. **  @defstatus must be 'defaulton' or 'defaultoff'
  5238. */
  5239. raiserror(15140,-1,-1)
  5240.  
  5241. return (1) -- sp_diskdefault
  5242. go
  5243.  
  5244. checkpoint
  5245. go
  5246.  
  5247.  
  5248. raiserror(15339,-1,-1,'sp_dropdevice')
  5249. go
  5250. create procedure sp_dropdevice --- 1996/04/08 00:00
  5251. @logicalname    sysname,        -- logical name of the device
  5252. @delfile    varchar(7) = null    -- optional param. to delete disk file
  5253. as
  5254.  
  5255. declare @physname nvarchar(260)
  5256. declare @ctrltype smallint
  5257. declare @cmd nvarchar(300)
  5258. /*
  5259. ** See if user specified something for @delfile and, if so, validate it.
  5260. */
  5261. if @delfile is not null
  5262.     begin
  5263.         select @delfile = lower(@delfile)
  5264.  
  5265.         if @delfile <> 'delfile'
  5266.             begin
  5267.                 raiserror(15216,-1,-1,@delfile)
  5268.                 return(1)
  5269.             end
  5270.     end
  5271.  
  5272. /*
  5273. **  If we're in a transaction, disallow this since it might make recovery
  5274. **  impossible.
  5275. */
  5276. set implicit_transactions off
  5277. if @@trancount > 0
  5278.     begin
  5279.         raiserror(15002,-1,-1,'sp_dropdevice')
  5280.         return (1)
  5281.     end
  5282.  
  5283. /*
  5284. **  Only the system administrator (SA) can run this command.
  5285. **  Check to make sure the executor is the sa.
  5286. */
  5287. if not is_srvrolemember('diskadmin') = 1
  5288.     begin
  5289.         raiserror(15003,-1,-1, 'diskadmin')
  5290.         return (1)
  5291.     end
  5292.  
  5293. /*
  5294. **  Check and make sure that the device actually exists.
  5295. */
  5296. if not exists (select * from master.dbo.sysdevices where name = @logicalname)
  5297.     begin
  5298.         raiserror(15012,-1,-1,@logicalname)
  5299.         return (1)
  5300.     end
  5301.  
  5302.  
  5303. select @physname = phyname,@ctrltype = cntrltype
  5304.         from master.dbo.sysdevices
  5305.         where name = @logicalname
  5306.  
  5307. if @ctrltype <> 6    -- Can't release file handle for 'pipe' device.
  5308.     begin
  5309.         raiserror(15462, -1,-1, @physname )
  5310.  
  5311.         /*
  5312.         ** Drop the device.
  5313.         */
  5314.         raiserror(15463,-1,-1)
  5315.  
  5316.         if @delfile = 'delfile'
  5317.             dbcc dbrepair
  5318.             ('', 'dropdevice',@logicalname, 1)  WITH NO_INFOMSGS
  5319.         else
  5320.             dbcc dbrepair
  5321.             ('', 'dropdevice',@logicalname, 0)  WITH NO_INFOMSGS
  5322.  
  5323.     end
  5324.  
  5325. return (0) -- sp_dropdevice
  5326. go
  5327.  
  5328.  
  5329. raiserror(15339,-1,-1,'sp_dropmessage')
  5330. go
  5331. create procedure sp_dropmessage --- 1996/04/08 00:00
  5332. @msgnum int = null,        -- Number of message to drop.
  5333. @lang sysname = null    -- Language of message to drop (or 'ALL')
  5334. as
  5335. declare @retcode int
  5336. declare @msglangid smallint
  5337.  
  5338. /*
  5339. ** If no message id, show usage
  5340. */
  5341. if @msgnum is null
  5342.     begin
  5343.         raiserror(15177,-1,-1)
  5344.         return (1)
  5345.     end
  5346.  
  5347. /*
  5348. ** Message id must be > 50000
  5349. */
  5350. if @msgnum < 50001
  5351.     begin
  5352.         raiserror(15178,-1,-1)
  5353.         return(1)
  5354.     end
  5355.  
  5356. if (select count(*) from master.dbo.sysmessages where error=@msgnum) = 0
  5357.     begin
  5358.         raiserror(15179,-1,-1,@msgnum)
  5359.         return(1)
  5360.     end
  5361.  
  5362. /*
  5363. ** Verify the language
  5364. */
  5365. if @lang is null
  5366.     select @lang = @@language
  5367. if upper(@lang) <> 'ALL'
  5368. begin
  5369.     begin
  5370.         exec @retcode = sp_validlang @lang
  5371.         if @retcode <>  0
  5372.             return(1)
  5373.     end
  5374.     /*
  5375.     ** Get langid from syslanguages; us_english won't exist, so use 0.
  5376.     */
  5377.     select @msglangid = isnull((select msglangid from master.dbo.syslanguages where name = @lang or alias = @lang),1033)
  5378. end
  5379.  
  5380. /*
  5381. ** The us_english version must be the last one to be dropped
  5382. */
  5383. if (@msglangid = 1033) and (select count(*) from master.dbo.sysmessages where error = @msgnum) > 1
  5384. begin
  5385.     raiserror(15280,-1,-1)
  5386.     return(1)
  5387. end
  5388.  
  5389. /*
  5390. **  Drop the message.
  5391. */
  5392. if upper(@lang) = 'ALL'
  5393.     delete from master.dbo.sysmessages where error = @msgnum
  5394. else
  5395.     delete from master.dbo.sysmessages where error = @msgnum and msglangid = @msglangid
  5396.  
  5397. raiserror(15466,-1,-1)
  5398. return (0) -- sp_dropmessage
  5399. go
  5400.  
  5401.  
  5402. raiserror(15339,-1,-1,'sp_droptype')
  5403. go
  5404. create procedure sp_droptype --- 1996/04/08 00:00
  5405. @typename sysname            /* the user type to drop */
  5406. as
  5407.  
  5408. declare @typeid smallint        /* the typeid of the usertype to drop */
  5409.  
  5410. /*
  5411. **  Initialize @typeid so we can tell if we can't find it.
  5412. */
  5413. select @typeid = 0
  5414.  
  5415. /*
  5416. **  Find the user type with @typename.  It must be a user type (xusertype > 256)
  5417. **  and it must be owned by the person (or special role) running the procedure.
  5418. */
  5419. select @typeid = xusertype
  5420.     from systypes
  5421.         where name = @typename and xusertype > 256
  5422.         AND (is_member('db_owner') = 1 OR is_member('db_ddladmin') = 1 OR is_member(user_name(uid))=1)
  5423.  
  5424. if @typeid = 0
  5425.     begin
  5426.         raiserror(15105,-1,-1)
  5427.         return (1)
  5428.     end
  5429.  
  5430. /*
  5431. **  Check to see if the type is being used.  If it is, it can't be dropped.
  5432. */
  5433. if exists (select * from syscolumns where xusertype = @typeid)
  5434.     begin
  5435.         raiserror(15180,-1,-1)
  5436.  
  5437.         /*
  5438.         **  Show where it's being used.
  5439.         */
  5440.         select object = o.name, type = o.xtype, owner = u.name,
  5441.             [column] = c.name, datatype = t.name
  5442.         from syscolumns c, systypes t, sysusers u, sysobjects o
  5443.         where c.xusertype = @typeid
  5444.             and t.xusertype = @typeid
  5445.             and o.uid = u.uid
  5446.             and c.id = o.id
  5447.         order by object, [column]
  5448.  
  5449.         return (1)
  5450.     end
  5451.  
  5452. /*
  5453. **  Everything is consistent so drop the type.
  5454. */
  5455. delete from systypes where xusertype = @typeid
  5456.  
  5457. raiserror(15467,-1,-1)
  5458.  
  5459. return (0) -- sp_droptype
  5460. go
  5461.  
  5462.  
  5463. checkpoint
  5464. go
  5465.  
  5466. raiserror(15339,-1,-1,'sp_dropremotelogin')
  5467. go
  5468. create procedure sp_dropremotelogin --- 1996/04/08 00:00
  5469.     @remoteserver    sysname,        /* name of remote server */
  5470.     @loginame sysname = NULL,        /* user's local user name */
  5471.     @remotename sysname = NULL        /* user's remote name */
  5472. as
  5473.     declare @srvid smallint
  5474.     declare @sid varbinary(85)
  5475.     declare @count int
  5476.  
  5477.     -- DISALLOW USER XACT --
  5478.     set implicit_transactions off
  5479.     if @@trancount > 0
  5480.     begin
  5481.         raiserror(15002,-1,-1,'sp_dropremotelogin')
  5482.         return (1)
  5483.     end
  5484.  
  5485.     -- CHECK PERMISSIONS
  5486.     if not (is_srvrolemember('securityadmin') = 1)
  5487.     begin
  5488.         raiserror(15232,-1,-1)
  5489.         return (1)
  5490.     end
  5491.  
  5492.     -- VALIDATE SERVER NAME --
  5493.     select @srvid = srvid from master.dbo.sysservers where srvname = @remoteserver
  5494.     if @srvid is null
  5495.     begin
  5496.         raiserror(15015,-1,-1,@remoteserver)
  5497.         return (1)
  5498.     end
  5499.  
  5500.     -- CHECK FOR INVALID PARAMETER SYNTAX --
  5501.     if @loginame is null and @remotename is not null
  5502.     begin
  5503.         raiserror(15600,-1,-1,'sp_dropremotelogin')
  5504.         return (1)
  5505.     end
  5506.  
  5507.     -- VALIDATE @loginame --
  5508.     if @loginame is not null
  5509.     begin
  5510.         select @sid = sid from master.dbo.syslogins where loginname = @loginame
  5511.                     AND isntname = 0        -- cannot remap to NT login
  5512.         if @sid is null
  5513.         begin
  5514.             raiserror(15067,-1,-1,@loginame)
  5515.             return (1)
  5516.         end
  5517.     end
  5518.  
  5519.     -- First remove the isrpcinmap bit from all rows which are also outmap
  5520.     update master.dbo.sysxlogins set xstatus = xstatus & ~32    -- isrpcinmap bit
  5521.         where srvid = @srvid AND isrpcinmap = 1 AND ishqoutmap = 1
  5522.             AND ((@sid IS NULL and sid IS NULL) or sid = @sid)
  5523.             AND ((@remotename IS NULL and name IS NULL) or name = @remotename)
  5524.  
  5525.     select @count = @@rowcount
  5526.  
  5527.     -- Delete the remote login(s) - the remaining rows with isrpcinmap set.
  5528.     delete master.dbo.sysxlogins where srvid = @srvid AND isrpcinmap = 1
  5529.             AND ((sid IS NULL and @sid IS NULL) or sid = @sid)
  5530.             AND ((@remotename IS NULL and name IS NULL) or name = @remotename)
  5531.  
  5532.     select @count = @count + @@rowcount
  5533.  
  5534.     -- IF NO ROWS UPDATED OR DELETED, ERROR --
  5535.     if @count = 0
  5536.     begin
  5537.         if (@loginame IS NULL)
  5538.             raiserror(15021,-1,-1,@remoteserver)
  5539.         else if (@remotename IS NULL)
  5540.             raiserror(15027,-1,-1,@loginame,@remoteserver)
  5541.         else
  5542.             raiserror(15185,-1,-1,@remotename,@loginame,@remoteserver)
  5543.         return (1)
  5544.     end
  5545.  
  5546.     -- SUCCESS --
  5547.     raiserror(15468,-1,-1)
  5548.     return (0)    -- sp_dropremotelogin
  5549. go
  5550.  
  5551.  
  5552. raiserror(15339,-1,-1,'sp_helpconstraint')
  5553. go
  5554. create proc sp_helpconstraint
  5555.     @objname nvarchar(776)            -- the table to check for constraints
  5556.    ,@nomsg   varchar(5) = 'msg'        -- 'nomsg' supresses printing of TBName (sp_help)
  5557. as
  5558.     -- PRELIM
  5559.     set nocount on
  5560.  
  5561.     declare    @objid            int           -- the object id of the table
  5562.             ,@cnstdes        nvarchar(4000)-- string to build up index desc
  5563.             ,@cnstname        sysname       -- name of const. currently under consideration
  5564.             ,@i                int
  5565.             ,@cnstid        int
  5566.             ,@cnsttype        character(2)
  5567.             ,@keys            nvarchar(2078)    --Length (16*max_identifierLength)+(15*2)
  5568.             ,@dbname        sysname
  5569.  
  5570.     -- Create temp table
  5571.     create table #spcnsttab
  5572.     (
  5573.         cnst_id            int            NOT NULL
  5574.         ,cnst_type            nvarchar(146)NOT NULL   -- 128 for name + text for DEFAULT
  5575.         ,cnst_name            sysname        NOT NULL
  5576.         ,cnst_nonblank_name    sysname        NOT NULL
  5577.         ,cnst_2type            character(2)    NULL
  5578.         ,cnst_disabled        bit                NULL
  5579.         ,cnst_notrepl        bit                NULL
  5580.         ,cnst_keys            nvarchar(2078)    NULL    -- see @keys above for length descr
  5581.     )
  5582.  
  5583.     -- Check to see that the object names are local to the current database.
  5584.     select @dbname = parsename(@objname,3) 
  5585.  
  5586.     if @dbname is not null and @dbname <> db_name()
  5587.     begin
  5588.         raiserror(15250,-1,-1)
  5589.         return (1)
  5590.     end
  5591.  
  5592.     -- Check to see if the table exists and initialize @objid.
  5593.     select @objid = object_id(@objname)
  5594.     if @objid is NULL
  5595.     begin
  5596.         select @dbname=db_name()
  5597.         raiserror(15009,-1,-1,@objname,@dbname)
  5598.         return (1)
  5599.     end
  5600.  
  5601.     -- STATIC CURSOR OVER THE TABLE'S CONSTRAINTS
  5602.     declare cnst_csr insensitive cursor for
  5603.         select id, xtype, name from sysobjects where parent_obj = @objid
  5604.             and xtype in ('C ','PK','UQ','F ', 'D ')    -- ONLY 6.5 sysconstraints objects
  5605.         for read only
  5606.  
  5607.     -- Now check out each constraint, figure out its type and keys and
  5608.     -- save the info in a temporary table that we'll print out at the end.
  5609.     open cnst_csr
  5610.     fetch cnst_csr into @cnstid ,@cnsttype ,@cnstname
  5611.     while @@fetch_status >= 0
  5612.     begin
  5613.  
  5614.         if @cnsttype in ('PK','UQ')
  5615.         begin
  5616.             -- get indid and index description
  5617.             declare @indid smallint
  5618.             select    @indid = indid,
  5619.                     @cnstdes = case when @cnsttype = 'PK'
  5620.                                 then 'PRIMARY KEY' else 'UNIQUE' end
  5621.                              + case when (status & 16)=16
  5622.                                 then ' (clustered)' else ' (non-clustered)' end
  5623.             from    sysindexes
  5624.             where    name = object_name(@cnstid)
  5625.                     and id = @objid
  5626.  
  5627.             -- Format keys string
  5628.             declare @thiskey sysname
  5629.             select @keys = index_col(@objname, @indid, 1), @i = 2,
  5630.                     @thiskey = index_col(@objname, @indid, 2)
  5631.             while (@thiskey is not null )
  5632.             begin
  5633.                 select @keys = @keys + ', ' + @thiskey, @i = @i + 1
  5634.                 select @thiskey = index_col(@objname, @indid, @i)
  5635.             end
  5636.  
  5637.             -- ADD TO TABLE
  5638.             insert into #spcnsttab
  5639.                 (cnst_id,cnst_type,cnst_name, cnst_nonblank_name,cnst_keys, cnst_2type)
  5640.             values (@cnstid, @cnstdes, @cnstname, @cnstname, @keys, @cnsttype)
  5641.         end
  5642.  
  5643.         else
  5644.         if @cnsttype = 'F '
  5645.         begin
  5646.             -- OBTAIN TWO TABLE IDs
  5647.             declare @fkeyid int, @rkeyid int
  5648.             select @fkeyid = fkeyid, @rkeyid = rkeyid from sysreferences where constid = @cnstid
  5649.  
  5650.             -- USE CURSOR OVER FOREIGN KEY COLUMNS TO BUILD COLUMN LISTS
  5651.             --    (NOTE: @keys HAS THE FKEY AND @cnstdes HAS THE RKEY COLUMN LIST)
  5652.             declare fkey_curs cursor for select fkey, rkey from sysforeignkeys where constid = @cnstid
  5653.             open fkey_curs
  5654.             declare @fkeycol smallint, @rkeycol smallint
  5655.             fetch fkey_curs into @fkeycol, @rkeycol
  5656.             select @keys = col_name(@fkeyid, @fkeycol), @cnstdes = col_name(@rkeyid, @rkeycol)
  5657.             fetch fkey_curs into @fkeycol, @rkeycol
  5658.             while @@fetch_status >= 0
  5659.             begin
  5660.                 select    @keys = @keys + ', ' + col_name(@fkeyid, @fkeycol),
  5661.                         @cnstdes = @cnstdes + ', ' + col_name(@rkeyid, @rkeycol)
  5662.                 fetch fkey_curs into @fkeycol, @rkeycol
  5663.             end
  5664.             deallocate fkey_curs
  5665.  
  5666.             -- ADD ROWS FOR BOTH SIDES OF FOREIGN KEY
  5667.             insert into #spcnsttab 
  5668.                 (cnst_id, cnst_type,cnst_name,cnst_nonblank_name,
  5669.                     cnst_keys, cnst_disabled, 
  5670.                     cnst_notrepl, cnst_2type)
  5671.             values 
  5672.                 (@cnstid, 'FOREIGN KEY', @cnstname, @cnstname,
  5673.                     @keys, ObjectProperty(@cnstid, 'CnstIsDisabled'),
  5674.                     ObjectProperty(@cnstid, 'CnstIsNotRepl'), @cnsttype)
  5675.             insert into #spcnsttab
  5676.                 (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,
  5677.                     cnst_keys,
  5678.                     cnst_2type)
  5679.             select
  5680.                 @cnstid,' ', ' ', @cnstname,
  5681.                     'REFERENCES ' + db_name()
  5682.                         + '.' + rtrim(user_name(ObjectProperty(@rkeyid,'ownerid')))
  5683.                         + '.' + object_name(@rkeyid) + ' ('+@cnstdes + ')',
  5684.                     @cnsttype
  5685.         end
  5686.  
  5687.         else
  5688.         if @cnsttype = 'C '
  5689.         begin
  5690.             select @i = 1
  5691.             select @cnstdes = text from syscomments where id = @cnstid and colid = @i
  5692.             while @cnstdes is not null
  5693.             begin
  5694.                 if @i=1
  5695.                     -- Check constraint
  5696.                     insert into    #spcnsttab
  5697.                         (cnst_id, cnst_type ,cnst_name ,cnst_nonblank_name,
  5698.                             cnst_keys, cnst_disabled, cnst_notrepl, cnst_2type)
  5699.                     select    @cnstid, 
  5700.                         case when info = 0 then 'CHECK Table Level '
  5701.                             else 'CHECK on column ' + col_name(@objid ,info) end,
  5702.                         @cnstname ,@cnstname ,substring(@cnstdes,1,2000),
  5703.                         ObjectProperty(@cnstid, 'CnstIsDisabled'),
  5704.                         ObjectProperty(@cnstid, 'CnstIsNotRepl'),
  5705.                         @cnsttype
  5706.                     from sysobjects    where id = @cnstid
  5707.                 else
  5708.                     insert into #spcnsttab (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,cnst_keys, cnst_2type)
  5709.                     select    @cnstid,' ' ,' ' ,@cnstname ,substring(@cnstdes,1,2000), @cnsttype
  5710.  
  5711.                 if len(@cnstdes) > 2000
  5712.                     insert into #spcnsttab (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,cnst_keys, cnst_2type)
  5713.                     select    @cnstid,' ' ,' ' ,@cnstname ,substring(@cnstdes,2001,2000), @cnsttype
  5714.  
  5715.                 select @cnstdes = null
  5716.                 select @i = @i + 1
  5717.                 select @cnstdes = text from syscomments where id = @cnstid and colid = @i
  5718.             end
  5719.         end
  5720.  
  5721.         else
  5722.         if (@cnsttype = 'D ')
  5723.         begin
  5724.             select @i = 1
  5725.             select @cnstdes = text from syscomments where id = @cnstid and colid = @i
  5726.             while @cnstdes is not null
  5727.             begin
  5728.                 if @i=1
  5729.                     insert into    #spcnsttab
  5730.                         (cnst_id,cnst_type ,cnst_name ,cnst_nonblank_name ,cnst_keys, cnst_2type)
  5731.                     select @cnstid, 'DEFAULT on column ' + col_name(@objid ,info),
  5732.                         @cnstname ,@cnstname ,@cnstdes, @cnsttype
  5733.                     from sysobjects where id = @cnstid
  5734.                 else
  5735.                     insert into #spcnsttab (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,cnst_keys, cnst_2type)
  5736.                     select    @cnstid,' ' ,' ' ,@cnstname ,@cnstdes, @cnsttype
  5737.  
  5738.                 select @i = @i + 1
  5739.                 select @cnstdes = null
  5740.                 select @cnstdes = text from syscomments where id = @cnstid and colid = @i
  5741.             end
  5742.         end
  5743.  
  5744.         fetch cnst_csr into @cnstid ,@cnsttype ,@cnstname
  5745.     end        --of major loop
  5746.     deallocate cnst_csr
  5747.  
  5748.     -- Find any rules or defaults bound by the sp_bind... method.
  5749.     insert into #spcnsttab (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,cnst_keys, cnst_2type)
  5750.     select c.domain,'RULE on column ' + c.name + ' (bound with sp_bindrule)',
  5751.         object_name(c.domain), object_name(c.domain), text, 'R '
  5752.     from    syscolumns c, syscomments m
  5753.     where    c.id = @objid and m.id = c.domain and ObjectProperty(c.domain, 'IsRule') = 1
  5754.  
  5755.     insert into #spcnsttab (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,cnst_keys, cnst_2type)
  5756.     select c.cdefault, 'DEFAULT on column ' + c.name + ' (bound with sp_bindefault)',
  5757.         object_name(c.cdefault),object_name(c.cdefault), text, 'D '
  5758.     from    syscolumns c,syscomments m
  5759.     where    c.id = @objid and m.id = c.cdefault and ObjectProperty(c.cdefault, 'IsConstraint') = 0
  5760.  
  5761.  
  5762.     -- OUTPUT RESULTS: FIRST THE OBJECT NAME (if not suppressed)
  5763.     if @nomsg <> 'nomsg'
  5764.     begin
  5765.         select 'Object Name' = @objname
  5766.         print ' '
  5767.     end
  5768.  
  5769.     -- Now print out the contents of the temporary index table.
  5770.     if exists (select * from #spcnsttab)
  5771.         select
  5772.             'constraint_type' = cnst_type,
  5773.             'constraint_name' = cnst_name,
  5774.             'status_enabled' =
  5775.                     CASE
  5776.                         When cnst_name = ' ' Then ' '
  5777.                         When cnst_2type in ('F ','C ') Then
  5778.                             CASE When cnst_disabled = 1
  5779.                                 then 'Disabled' else 'Enabled' end
  5780.                         Else '(n/a)'
  5781.                     END,
  5782.             'status_for_replication' =
  5783.                     CASE
  5784.                         When cnst_name = ' ' Then ' '
  5785.                         When cnst_2type in ('F ','C ') Then
  5786.                             CASE When cnst_notrepl = 1
  5787.                                 Then 'Not_For_Replication' else 'Is_For_Replication' end
  5788.                         Else '(n/a)'
  5789.                     END,
  5790.             'constraint_keys' = cnst_keys
  5791.         from #spcnsttab order by cnst_nonblank_name ,cnst_name desc
  5792.     else
  5793.         raiserror(15469,-1,-1) --'No constraints have been defined for this object.'
  5794.  
  5795.     print ' '
  5796.  
  5797.     if exists (select * from sysreferences where rkeyid = @objid)
  5798.         select
  5799.             'Table is referenced by ' =
  5800.                 db_name() + '.'
  5801.                     + rtrim(user_name(ObjectProperty(fkeyid,'ownerid')))
  5802.                     + '.' + object_name(fkeyid)
  5803.                     + ': ' + object_name(constid)
  5804.             from sysreferences where rkeyid = @objid order by 1
  5805.     else
  5806.         raiserror(15470,-1,-1) --'No foreign keys reference this table.'
  5807.  
  5808.     return (0) -- sp_helpconstraint
  5809. go
  5810.  
  5811. checkpoint
  5812. go
  5813.  
  5814.  
  5815. raiserror(15339,-1,-1,'sp_helpdb')
  5816. go
  5817. create procedure sp_helpdb  --- 1995/12/20 15:34 #12755
  5818. @dbname sysname = NULL            /* database name to change */
  5819. as
  5820.  
  5821. declare @exec_stmt nvarchar(625)
  5822. declare @showdev    bit
  5823. declare @allstatopts    int
  5824. declare @allrelstatopts    int
  5825. declare @allcatopts    int
  5826. declare @name           sysname
  5827. declare @cmd    nvarchar(279)
  5828.  
  5829. set nocount on
  5830.  
  5831. /*    Create temp table before any DMP to enure dynamic
  5832. **  Since we examine the status bits in sysdatabase and turn them
  5833. **  into english, we need a temporary table to build the descriptions.
  5834. */
  5835. create table #spdbdesc
  5836. (
  5837.     dbid    smallint    null,
  5838.     dbdesc    varchar(340)    null
  5839. )
  5840.  
  5841. /* 
  5842. ** Since we need to execute dynamic SQL to get the list of files, create a temp 
  5843. ** table to keep file descriptions
  5844. */
  5845. create table #spfiledesc
  5846. (
  5847.     dbid    smallint        not null,
  5848.     fileid     smallint        not null,
  5849.     status  int                not null,
  5850.     size    int             not null,
  5851.     name    sysname         not null,
  5852. )    
  5853.  
  5854. /*
  5855. **  If no database name given, get 'em all.
  5856. */
  5857. if @dbname is null
  5858.     select @showdev = 0
  5859. else select @showdev = 1
  5860.  
  5861. /*
  5862. **  See if the database exists
  5863. */
  5864. if not exists (select * from master.dbo.sysdatabases 
  5865.     where (@dbname is null or name = @dbname))
  5866.     begin
  5867.         raiserror(15010,-1,-1,@dbname)
  5868.         return (1)
  5869.     end
  5870.  
  5871. /*
  5872. ** Get bitmap of all options that can be set by sp_dboption.
  5873. */
  5874. select @allstatopts=number from master.dbo.spt_values
  5875.     where type = 'D' and name = 'ALL SETTABLE OPTIONS'
  5876. select @allrelstatopts=number from master.dbo.spt_values
  5877.     where type = 'D2' and name = 'ALL SETTABLE OPTIONS'
  5878. select @allcatopts=number from master.dbo.spt_values
  5879.     where type = 'DC' and name = 'ALL SETTABLE OPTIONS'
  5880.  
  5881. /*
  5882. **  Initialize #spdbdesc from sysdatabases
  5883. */
  5884. insert into #spdbdesc (dbid)
  5885.         select dbid from master.dbo.sysdatabases
  5886.             where (@dbname is null or name = @dbname)
  5887.  
  5888. /* 
  5889. ** Check if you have access to database
  5890. */
  5891. declare access_check cursor for 
  5892.     select db_name (dbid) from #spdbdesc
  5893. open access_check
  5894. fetch access_check into @name
  5895. while @@fetch_status >= 0
  5896. begin
  5897.     if (has_dbaccess(@name) <> 1)
  5898.     begin
  5899.       delete #spdbdesc where current of access_check
  5900.       raiserror(15622,-1,-1, @name)
  5901.     end
  5902.     fetch access_check into @name
  5903. end
  5904. deallocate access_check
  5905.  
  5906. /* 
  5907. ** Insert the list of all files into #spfiledesc
  5908. */
  5909. declare c1 cursor for 
  5910.     select db_name (dbid) from #spdbdesc
  5911. open c1
  5912. fetch c1 into @name
  5913. while @@fetch_status >= 0
  5914. begin
  5915.  
  5916.     /* Insert row for each database */
  5917.     select @exec_stmt = 'insert into #spfiledesc
  5918.             select db_id (N'+ quotename(@name, '''') + '), fileid, status, size, name from ' 
  5919.              + quotename(@name, '[') + '.dbo.sysfiles'
  5920.     execute (@exec_stmt)
  5921.     fetch c1 into @name
  5922. end
  5923. deallocate c1
  5924.  
  5925. /*
  5926. **  Now for each dbid in #spdbdesc, build the database status
  5927. **  description.
  5928. */
  5929. declare @curdbid smallint    /* the one we're currently working on */
  5930. declare @dbdesc varchar(340)    /* the total description for the db */
  5931. declare @bitdesc varchar(35)    /* the bit description for the db */
  5932.  
  5933. /*
  5934. **  Set @curdbid to the first dbid.
  5935. */
  5936. select @curdbid = min(dbid) from #spdbdesc
  5937.  
  5938. while @curdbid IS NOT NULL
  5939. begin
  5940.     /*
  5941.     **  Initialize @dbdesc.
  5942.     */
  5943.     select @dbdesc = ''
  5944.  
  5945.     /*
  5946.     ** First check bits in sysdatabases.status.
  5947.     */
  5948.  
  5949.     /*
  5950.     **  Check select into/bulk copy bit (4)
  5951.     */
  5952.     select @bitdesc = null
  5953.     select @bitdesc = v.name
  5954.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  5955.         where d.dbid = @curdbid
  5956.             and v.type = 'D'
  5957.             and d.status & v.number = 4
  5958.             and v.number <> @allstatopts       /* all status options */
  5959.     if @bitdesc IS NOT NULL
  5960.     begin
  5961.         if @dbdesc <> ''
  5962.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  5963.         else select @dbdesc = @bitdesc
  5964.     end
  5965.  
  5966.     /*
  5967.     **  Check truncate log on checkpoint bit (8)
  5968.     */
  5969.     select @bitdesc = null
  5970.     select @bitdesc = v.name
  5971.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  5972.         where d.dbid = @curdbid
  5973.             and v.type = 'D'
  5974.             and d.status & v.number = 8
  5975.             and v.number <> @allstatopts       /* all status options */
  5976.     if @bitdesc IS NOT NULL
  5977.     begin
  5978.         if @dbdesc <> ''
  5979.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  5980.         else select @dbdesc = @bitdesc
  5981.     end
  5982.  
  5983.     /*
  5984.     **  Check no checkpoint on recovery bit (16)
  5985.     */
  5986.     select @bitdesc = null
  5987.     select @bitdesc = v.name
  5988.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  5989.         where d.dbid = @curdbid
  5990.             and v.type = 'D'
  5991.             and d.status & v.number = 16
  5992.             and v.number <> @allstatopts /* all status options */
  5993.     if @bitdesc IS NOT NULL
  5994.     begin
  5995.         if @dbdesc <> ''
  5996.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  5997.         else select @dbdesc = @bitdesc
  5998.     end
  5999.  
  6000.     /*
  6001.     **  Check don't recover bit (32)
  6002.     */
  6003.     select @bitdesc = null
  6004.     select @bitdesc = v.name
  6005.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6006.         where d.dbid = @curdbid
  6007.             and v.type = 'D'
  6008.             and d.status & v.number = 32
  6009.             and v.number <> @allstatopts       /* all status options */
  6010.     if @bitdesc IS NOT NULL
  6011.     begin
  6012.         if @dbdesc <> ''
  6013.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6014.         else select @dbdesc = @bitdesc
  6015.     end
  6016.  
  6017.     /*
  6018.     **  Check not recovered only bit (256)
  6019.     */
  6020.     select @bitdesc = null
  6021.     select @bitdesc = v.name
  6022.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6023.         where d.dbid = @curdbid
  6024.             and v.type = 'D'
  6025.             and d.status & v.number = 256
  6026.             and v.number <> @allstatopts       /* all status options */
  6027.     if @bitdesc IS NOT NULL
  6028.     begin
  6029.         if @dbdesc <> ''
  6030.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6031.         else select @dbdesc = @bitdesc
  6032.     end
  6033.  
  6034.     /*
  6035.     **  Check offline bit (512)
  6036.     */
  6037.     select @bitdesc = null
  6038.     select @bitdesc = v.name
  6039.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6040.         where d.dbid = @curdbid
  6041.             and v.type = 'D'
  6042.             and d.status & v.number = 512
  6043.             and v.number <> @allstatopts       /* all status options */
  6044.     if @bitdesc IS NOT NULL
  6045.     begin
  6046.         if @dbdesc <> ''
  6047.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6048.         else select @dbdesc = @bitdesc
  6049.     end
  6050.  
  6051.     /*
  6052.     **  Check read only bit (1024)
  6053.     */
  6054.     select @bitdesc = null
  6055.     select @bitdesc = v.name
  6056.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6057.         where d.dbid = @curdbid
  6058.             and v.type = 'D'
  6059.             and d.status & v.number = 1024
  6060.             and v.number <> @allstatopts       /* all status options */
  6061.     if @bitdesc IS NOT NULL
  6062.     begin
  6063.         if @dbdesc <> ''
  6064.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6065.         else select @dbdesc = @bitdesc
  6066.     end
  6067.  
  6068.     /*
  6069.     **  Check dbo only bit (2048)
  6070.     */
  6071.     select @bitdesc = null
  6072.     select @bitdesc = v.name
  6073.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6074.         where d.dbid = @curdbid
  6075.             and v.type = 'D'
  6076.             and d.status & v.number = 2048
  6077.             and v.number <> @allstatopts       /* all status options */
  6078.     if @bitdesc IS NOT NULL
  6079.     begin
  6080.         if @dbdesc <> ''
  6081.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6082.         else select @dbdesc = @bitdesc
  6083.     end
  6084.  
  6085.     /*
  6086.     **  Check single user bit (4096)
  6087.     */
  6088.     select @bitdesc = null
  6089.     select @bitdesc = v.name
  6090.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6091.         where d.dbid = @curdbid
  6092.             and v.type = 'D'
  6093.             and d.status & v.number = 4096
  6094.             and v.number <> @allstatopts       /* all status options */
  6095.     if @bitdesc IS NOT NULL
  6096.     begin
  6097.         if @dbdesc <> ''
  6098.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6099.         else select @dbdesc = @bitdesc
  6100.     end
  6101.  
  6102.     /*
  6103.     **  Check ANSI NULL default bit (16384)
  6104.     */
  6105.     select @bitdesc = null
  6106.     select @bitdesc = v.name
  6107.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6108.         where d.dbid = @curdbid
  6109.             and v.type = 'D2'
  6110.             and d.status & v.number = 16384
  6111.             and v.number <> @allrelstatopts       /* all status options */
  6112.     if @bitdesc IS NOT NULL
  6113.     begin
  6114.         if @dbdesc <> ''
  6115.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6116.         else select @dbdesc = @bitdesc
  6117.     end
  6118.  
  6119.     /*
  6120.     **  Check ANSI empty string bit (65536)
  6121.     */
  6122.     select @bitdesc = null
  6123.     select @bitdesc = v.name
  6124.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6125.         where d.dbid = @curdbid
  6126.             and v.type = 'D2'
  6127.             and d.status & v.number = 65536
  6128.             and v.number <> @allrelstatopts       /* all status options */
  6129.     if @bitdesc IS NOT NULL
  6130.     begin
  6131.         if @dbdesc <> ''
  6132.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6133.         else select @dbdesc = @bitdesc
  6134.     end
  6135.  
  6136.     /*
  6137.     **  Check recursive triggers bit (131072)
  6138.     */
  6139.     select @bitdesc = null
  6140.     select @bitdesc = v.name
  6141.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6142.         where d.dbid = @curdbid
  6143.             and v.type = 'D2'
  6144.             and d.status & v.number = 131072
  6145.             and v.number <> @allrelstatopts       /* all status options */
  6146.     if @bitdesc IS NOT NULL
  6147.     begin
  6148.         if @dbdesc <> ''
  6149.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6150.         else select @dbdesc = @bitdesc
  6151.     end
  6152.  
  6153.     /*
  6154.     ** Now check bits in sysdatabases.category.
  6155.     */
  6156.  
  6157.     /*
  6158.     **  Check published bit (1)
  6159.     */
  6160.     select @bitdesc = null
  6161.     select @bitdesc = v.name
  6162.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6163.         where d.dbid = @curdbid
  6164.             and v.type = 'DC'
  6165.             and d.category & v.number = 1
  6166.             and v.number <> @allcatopts       /* all options */
  6167.     if @bitdesc IS NOT NULL
  6168.     begin
  6169.         if @dbdesc <> ''
  6170.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6171.         else select @dbdesc = @bitdesc
  6172.     end
  6173.  
  6174.  
  6175.     /*
  6176.     **  Check subscribed bit (2)
  6177.     */
  6178.     select @bitdesc = null
  6179.     select @bitdesc = v.name
  6180.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6181.         where d.dbid = @curdbid
  6182.             and v.type = 'DC'
  6183.             and d.category & v.number = 2
  6184.             and v.number <> @allcatopts       /* all options */
  6185.     if @bitdesc IS NOT NULL
  6186.     begin
  6187.         if @dbdesc <> ''
  6188.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6189.         else select @dbdesc = @bitdesc
  6190.     end
  6191.  
  6192.     /*
  6193.     **  Check merge publish bit (4)
  6194.     */
  6195.     select @bitdesc = null
  6196.     select @bitdesc = v.name
  6197.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6198.         where d.dbid = @curdbid
  6199.             and v.type = 'DC'
  6200.             and d.category & v.number = 4
  6201.             and v.number <> @allcatopts       /* all options */
  6202.     if @bitdesc IS NOT NULL
  6203.     begin
  6204.         if @dbdesc <> ''
  6205.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6206.         else select @dbdesc = @bitdesc
  6207.     end
  6208.  
  6209.     /*
  6210.     **  Check distributed bit (16)
  6211.     */
  6212.     select @bitdesc = null
  6213.     select @bitdesc = v.name
  6214.         from master.dbo.spt_values v, master.dbo.sysdatabases d
  6215.         where d.dbid = @curdbid
  6216.             and v.type = 'DC'
  6217.             and d.category & v.number = 16
  6218.             and v.number <> @allcatopts       /* all options */
  6219.     if @bitdesc IS NOT NULL
  6220.     begin
  6221.         if @dbdesc <> ''
  6222.             select @dbdesc = @dbdesc + ', ' +  @bitdesc
  6223.         else select @dbdesc = @bitdesc
  6224.     end
  6225.  
  6226.     /*
  6227.     **  If no flags are set, say so.
  6228.     */
  6229.     if @dbdesc = ''
  6230.         select @dbdesc = 'no options set'
  6231.  
  6232.     /*
  6233.     **  Save the description.
  6234.     */
  6235.     update #spdbdesc set dbdesc = @dbdesc
  6236.         from #spdbdesc
  6237.             where dbid = @curdbid
  6238.  
  6239.     /*
  6240.     **  Now get the next, if any dbid.
  6241.     */
  6242.     select @curdbid = min(dbid) from #spdbdesc where dbid > @curdbid
  6243. end
  6244.  
  6245. /*
  6246. **  Now #spdbdesc is complete so we can print out the db info
  6247. */
  6248. select name = substring(d.name, 1, 24),
  6249.     db_size = str(sum(convert(dec(15),v.size))*
  6250.         (select low from master.dbo.spt_values
  6251.             where type = 'E' and number = 1)
  6252.              / 1048576,10,2)+ ' MB',
  6253.     owner = substring(suser_sname(d.sid), 1, 24),
  6254.     dbid = d.dbid,
  6255.     created = convert(char(11), d.crdate),
  6256.     status = s.dbdesc
  6257. from master.dbo.sysdatabases d, #spfiledesc v, #spdbdesc s
  6258. where d.dbid = s.dbid
  6259.     and s.dbid = v.dbid
  6260. group by d.name,d.sid,d.dbid,d.crdate,s.dbdesc
  6261. order by d.name
  6262.  
  6263. /*
  6264. **  If we are looking at one database, show its file allocation.
  6265. */
  6266. if @showdev = 1 and has_dbaccess(@dbname) = 1
  6267. begin
  6268.     print ' '
  6269.     select @cmd = 'use ' +  quotename(@dbname) + ' exec sp_helpfile'
  6270.     exec (@cmd)
  6271.  
  6272. end
  6273. return (0) -- sp_helpdb
  6274. go
  6275.  
  6276.  
  6277.  
  6278.  
  6279. raiserror(15339,-1,-1,'sp_helpdevice')
  6280. go
  6281. create procedure sp_helpdevice --- 1996/04/08 00:00
  6282. @devname sysname = NULL        /* device to check out */
  6283. as
  6284.  
  6285. /*    Create temp tables before any DML to ensure dynamic
  6286. **  Create a temporary table where we can build up a translation of
  6287. **  the device status bits.
  6288. */
  6289. create table #spdevtab
  6290. (
  6291.     name sysname        NOT NULL,
  6292.     statusdesc varchar(255)    null
  6293. )
  6294. /*
  6295. **  See if the device exists.
  6296. */
  6297.  
  6298. if not exists (select * from master.dbo.sysdevices where 
  6299.     (@devname is null or name = @devname))
  6300.     begin
  6301.         raiserror(15012,-1,-1,@devname)
  6302.         return (1)
  6303.     end
  6304.  
  6305. set nocount on
  6306.  
  6307. /*
  6308. **  Initialize the temporary table with the names of the devices.
  6309. */
  6310. insert into #spdevtab (name)
  6311.     select name
  6312.         from master.dbo.sysdevices
  6313.         where (@devname is null or name = @devname)
  6314.  
  6315.  
  6316. /*
  6317. **  Now figure out what kind of controller type it is.
  6318. **
  6319. **  cntrltype =            0    special (data disk)
  6320. **                2    disk (dump)
  6321. **                3-4    floppy (dump)    Not supported in SQL 7.0
  6322. **                5    tape            No size information in SQL 7.0
  6323. **                6    pipe
  6324. **                7    virtual_device
  6325. */
  6326. update #spdevtab
  6327.     set statusdesc = 'special'
  6328.         from master.dbo.sysdevices d, #spdevtab
  6329.             where d.cntrltype = 0
  6330.                 and #spdevtab.name = d.name
  6331. update #spdevtab
  6332.     set statusdesc = 'disk'
  6333.         from master.dbo.sysdevices d, #spdevtab
  6334.             where d.cntrltype = 2
  6335.                 and #spdevtab.name = d.name
  6336.  
  6337. update #spdevtab
  6338.     set statusdesc = 'tape'
  6339.         from master.dbo.sysdevices d, #spdevtab
  6340.             where d.cntrltype = 5
  6341.                 and #spdevtab.name = d.name
  6342.  
  6343. update #spdevtab
  6344.     set statusdesc = 'pipe'
  6345.         from master.dbo.sysdevices d, #spdevtab
  6346.             where d.cntrltype = 6
  6347.                 and #spdevtab.name = d.name
  6348. update #spdevtab
  6349.     set statusdesc = 'virtual_device'
  6350.         from master.dbo.sysdevices d, #spdevtab
  6351.             where d.cntrltype = 7
  6352.                 and #spdevtab.name = d.name
  6353.  
  6354. update #spdevtab
  6355.     set statusdesc = 'UNKNOWN DEVICE'
  6356.         from master.dbo.sysdevices d, #spdevtab
  6357.             where d.cntrltype >= 8
  6358.                 and #spdevtab.name = d.name
  6359.  
  6360.  
  6361. /*
  6362. **  Now check out the status bits and turn them into english.
  6363. **  Status of 16 is a dump device.
  6364. */
  6365. update #spdevtab set statusdesc = statusdesc + ', ' + rtrim(v.name)
  6366.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6367.     where v.type = 'V' and v.number > -1
  6368.         and d.status & v.number = 16
  6369.         and #spdevtab.name = d.name
  6370.  
  6371. /*
  6372. **  Status of 1 is a default disk.
  6373. */
  6374. update #spdevtab set statusdesc = statusdesc + ', ' + rtrim(v.name)
  6375.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6376.     where v.type = 'V' and v.number > -1
  6377.         and d.status & v.number = 1
  6378.         and #spdevtab.name = d.name
  6379.  
  6380. /*
  6381. **  Status of 2 is a physical disk.
  6382. */
  6383. update #spdevtab
  6384.     set statusdesc = substring(statusdesc, 1, 225) + ', ' + rtrim(v.name)
  6385.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6386.     where v.type = 'V' and v.number > -1
  6387.         and d.status & v.number = 2
  6388.         and #spdevtab.name = d.name
  6389.  
  6390. /*
  6391. **  Add in its size in MB.
  6392. */
  6393. update #spdevtab
  6394.     set statusdesc = statusdesc + ', ' + convert(varchar(10),
  6395.         round((convert(float, d.size) * (select low from master.dbo.spt_values
  6396.             where type = 'E' and number = 1)
  6397.              / 1048576), 1)) + ' MB'
  6398.     from master.dbo.sysdevices d, #spdevtab, master.dbo.spt_values v
  6399.     where d.status & 2 = 2
  6400.         and #spdevtab.name = d.name
  6401.         and v.number = 1
  6402.         and v.type = 'E'
  6403.  
  6404. /*
  6405. **  Status of 4 is a logical disk.
  6406. */
  6407. update #spdevtab
  6408.     set statusdesc = substring(statusdesc, 1, 225) + ', ' + rtrim(v.name)
  6409.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6410.     where v.type = 'V' and v.number > -1
  6411.         and d.status & v.number = 4
  6412.         and #spdevtab.name = d.name
  6413.  
  6414. /*
  6415. **  Status of 8 is a skip tape header.
  6416. */
  6417. update #spdevtab
  6418.     set statusdesc = substring(statusdesc, 1, 225) + ', ' + rtrim(v.name)
  6419.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6420.     where v.type = 'V' and v.number > -1
  6421.         and d.status & v.number = 8
  6422.         and #spdevtab.name = d.name
  6423. /*
  6424. **  Status of 4096 is read only.
  6425. */
  6426. update #spdevtab
  6427.     set statusdesc = substring(statusdesc, 1, 225) + ', ' + rtrim(v.name)
  6428.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6429.     where v.type = 'V' and v.number > -1
  6430.         and d.status & v.number = 4096
  6431.         and #spdevtab.name = d.name
  6432. /*
  6433. **  Status of 8192 is deferred.
  6434. */
  6435. update #spdevtab
  6436.     set statusdesc = substring(statusdesc, 1, 225) + ', ' + (v.name)
  6437.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6438.     where v.type = 'V' and v.number > -1
  6439.         and d.status & v.number = 8192
  6440.         and #spdevtab.name = d.name
  6441.  
  6442. set nocount off
  6443.  
  6444. /*
  6445. **  The device number is in the high byte of sysdevices.low so
  6446. **  spt_values tells us which byte to pick out.
  6447. */
  6448. select device_name = d.name, physical_name = substring(d.phyname, 1, 46),
  6449.     description = #spdevtab.statusdesc,
  6450.     status = d.status&12319, d.cntrltype,
  6451.     size
  6452.     from master.dbo.sysdevices d, #spdevtab, master.dbo.spt_values v
  6453.     where d.name = #spdevtab.name
  6454.         and v.type = 'E'
  6455.         and v.number = 3
  6456.  
  6457. return(0) -- sp_helpdevice
  6458. go
  6459.  
  6460. raiserror(15339,-1,-1,'sp_helpfile')
  6461. go
  6462. create procedure sp_helpfile
  6463. @filename sysname = NULL            /* file name or all files */
  6464. as
  6465.  
  6466. set nocount on
  6467.  
  6468. if @filename IS NULL
  6469. begin
  6470. select     name,  fileid, filename, 
  6471.     filegroup = filegroup_name(groupid), 
  6472.     'size' = convert(nvarchar(15), size * 8) + N' KB',
  6473.     'maxsize' = (case maxsize when -1 then N'Unlimited' 
  6474.             else 
  6475.             convert(nvarchar(15), maxsize * 8) + N' KB' end),
  6476.     'growth' = (case status & 0x100000 when 0x100000 then
  6477.         convert(nvarchar(3), growth) + N'%'
  6478.         else
  6479.         convert(nvarchar(15), growth * 8) + N' KB' end),
  6480.     'usage' = (case status & 0x40 when 0x40 then 'log only' else 'data only' end)
  6481.     from sysfiles
  6482.     order by fileid
  6483.     
  6484. end
  6485. else
  6486. begin
  6487.     if file_id(@filename) IS NULL
  6488.     begin -- no such file
  6489.         raiserror (15325, -1, -1, 'file', @filename)
  6490.         return (1)
  6491.     end
  6492.     select     name,  filename, 
  6493.     filegroup = filegroup_name(groupid), 
  6494.     'size' = convert(nvarchar(15), size * 8) + N' KB',
  6495.     'maxsize' = (case maxsize when -1 then N'Unlimited' 
  6496.             else 
  6497.             convert(nvarchar(15), maxsize * 8) + N' KB' end),
  6498.     'growth' = (case status & 0x100000 when 0x100000 then
  6499.         convert(nvarchar(3), growth) + N'%'
  6500.         else
  6501.         convert(nvarchar(15), growth * 8) + N' KB' end),
  6502.     'usage' = (case status & 0x40 when 0x40 then 'log only' else 'data only' end)
  6503.     from sysfiles
  6504.     where fileid = file_id(@filename)
  6505.     order by fileid
  6506. end
  6507.  
  6508. return (0) -- sp_helpfile
  6509. go
  6510.  
  6511. raiserror(15339,-1,-1,'sp_helpfilegroup')
  6512. go
  6513. create procedure sp_helpfilegroup
  6514. @filegroupname sysname = NULL        /* filegroup name or all filegroups */
  6515. as
  6516.  
  6517. set nocount on
  6518. -- status & 0x40 is a log file and thus not in any filegroup
  6519. if @filegroupname IS NULL
  6520. begin
  6521.     select     g.groupname,  g.groupid, 'filecount' = 
  6522.         (select count(*) from sysfiles f 
  6523.             where f.groupid = g.groupid 
  6524.                 and (f.status & 0x40 <> 0x40))
  6525.     from sysfilegroups g
  6526. end
  6527. else
  6528. begin
  6529.     if (filegroup_id(@filegroupname) IS NULL)
  6530.     begin
  6531.         raiserror (15325, -1, -1, 'filegroup', @filegroupname)
  6532.         return (1)
  6533.     end
  6534.     select     g.groupname,  g.groupid, 'filecount' = 
  6535.         (select count(*) from sysfiles f 
  6536.             where f.groupid = g.groupid
  6537.                 and (f.status & 0x40 <> 0x40))
  6538.     from sysfilegroups g
  6539.     where g.groupid = filegroup_id(@filegroupname)
  6540.  
  6541.     select     'file_in_group' = name,  fileid, filename, 
  6542.     'size' = convert(nvarchar(15), size * 8) + N' KB',
  6543.     'maxsize' = (case maxsize when -1 then N'Unlimited' 
  6544.             else 
  6545.             convert(nvarchar(15), maxsize * 8) + N' KB' end),
  6546.     'growth' = (case status & 0x100000 when 0x100000 then
  6547.         convert(nvarchar(3), growth) + N'%'
  6548.         else
  6549.         convert(nvarchar(15), growth * 8) + N' KB' end)
  6550.     from sysfiles
  6551.     where groupid = filegroup_id(@filegroupname) 
  6552.     and (status & 0x40 <> 0x40)
  6553.     order by fileid
  6554. end
  6555.  
  6556. return (0) -- sp_helpfilegroup
  6557. go
  6558.  
  6559.  
  6560. raiserror(15339,-1,-1,'sp_helpgroup')
  6561. go
  6562. create procedure sp_helpgroup --- 1996/04/08 00:00
  6563. @grpname sysname = NULL        /* group name of interest */
  6564. as
  6565.  
  6566. /*
  6567. **  If no group name given, list all the groups.
  6568. */
  6569. if @grpname is null
  6570. begin
  6571.     select Group_name = name, Group_id = uid
  6572.         from sysusers
  6573.             where (issqlrole = 1)
  6574.         order by name
  6575.  
  6576.     return (0)
  6577. end
  6578.  
  6579. /*
  6580. **  Check to see if group exists.
  6581. */
  6582. if not exists (select * from sysusers where name = @grpname
  6583.         and (issqlrole = 1))
  6584.     begin
  6585.         raiserror(15014,-1,-1,@grpname)
  6586.         return (1)
  6587.     end
  6588.  
  6589. /*
  6590. **  List the particulars for the group.
  6591. */
  6592. select Group_name = substring(g.name, 1, 25), Group_id = g.uid,
  6593.        Users_in_group = substring(u.name, 1, 25),
  6594.        Userid = u.uid
  6595.     from sysusers u, sysusers g, sysmembers m
  6596.     where g.name = @grpname
  6597.         and g.uid = m.groupuid
  6598.         and (g.issqlrole = 1)
  6599.         and u.uid = m.memberuid
  6600.     order by 1, 2
  6601.  
  6602. return (0) -- sp_helpgroup
  6603. go
  6604.  
  6605.  
  6606.  
  6607.  
  6608.  
  6609. raiserror(15339,-1,-1,'sp_helplog')
  6610. go
  6611. create procedure sp_helplog --- 1996/04/08 00:00
  6612. as
  6613. declare @firstpage int,
  6614.     @devname nvarchar(257),
  6615.     @msg nvarchar(255)
  6616.  
  6617. raiserror('sp_helplog is no longer supported.',1,1)
  6618.  
  6619. return (0) -- sp_helplog
  6620. go
  6621.  
  6622.  
  6623.  
  6624. raiserror(15339,-1,-1,'sp_helplogins')
  6625. go
  6626. CREATE PROCEDURE sp_helplogins  --- 1996/08/12 14:34
  6627.  
  6628.     @LoginNamePattern     sysname    = NULL
  6629. AS
  6630.  
  6631. Set nocount on
  6632.  
  6633. Declare 
  6634.         @exec_stmt nvarchar(3550)
  6635.  
  6636. Declare
  6637.        @RetCode                        int
  6638.       ,@CountSkipPossUsers             int
  6639.       ,@Int1                           int
  6640.  
  6641. Declare
  6642.        @c10DBName                      sysname
  6643.       ,@c10DBStatus                    int
  6644.       ,@c10DBSID                       varbinary(85)
  6645.  
  6646. Declare
  6647.        @charMaxLenLoginName            varchar(11)
  6648.       ,@charMaxLenDBName               varchar(11)
  6649.       ,@charMaxLenUserName             varchar(11)
  6650.       ,@charMaxLenLangName             varchar(11)
  6651.  
  6652. Declare
  6653.        @DBOptLoading                   int   --0x0020      32  "DoNotRecover"
  6654.       ,@DBOptPreRecovery               int   --0x0040      64
  6655.       ,@DBOptRecovering                int   --0x0080     128
  6656.  
  6657.       ,@DBOptSuspect                   int   --0x0100     256  ("not recovered")
  6658.       ,@DBOptOffline                   int   --0x0200     512
  6659.       ,@DBOptDBOUseOnly                int   --0x0800    2048
  6660.  
  6661.       ,@DBOptSingleUser                int   --0x1000    4096
  6662.  
  6663.  
  6664. -------------  create work holding tables  ----------------
  6665. /*Create temp tables before any DML to ensure dynamic*/
  6666.  
  6667. CREATE Table #tb2_PlainLogins
  6668.    (
  6669.     LoginName                       sysname    NOT Null
  6670.    ,SID                             varchar(85)    NOT Null
  6671.    ,DefDBName                       sysname    NOT Null
  6672.    ,DefLangName                     sysname        Null
  6673.    ,AUser                           char(5)            Null
  6674.    ,ARemote                         char(7)            Null
  6675.    )
  6676.  
  6677. CREATE Table #tb1_UA
  6678.    (
  6679.     LoginName                       sysname        NOT Null
  6680.    ,DBName                          sysname        NOT Null
  6681.    ,UserName                        sysname        NOT Null
  6682.    ,UserOrAlias                     char(8)        NOT Null
  6683.    )
  6684.  
  6685. ----------------  Initial data values  -------------------
  6686.  
  6687. Select
  6688.        @RetCode                        = 0  -- 0=good ,1=bad
  6689.       ,@CountSkipPossUsers             = 0
  6690.  
  6691.  
  6692. ----------------  Only SA can run this  -------------------
  6693.  
  6694.  
  6695. IF (not (is_srvrolemember('securityadmin') = 1))
  6696.    begin
  6697.    raiserror(15003,-1,-1, 'securityadmin')
  6698.    Select @RetCode = 1
  6699.    goto label_86return
  6700.    end
  6701.  
  6702. ----------------------  spt_values  ----------------
  6703. -------- 'D'
  6704.  
  6705. SELECT       @DBOptLoading       = number
  6706.       from   master.dbo.spt_values
  6707.       where  type                = 'D'
  6708.       and    name                = 'loading'
  6709.  
  6710. SELECT       @DBOptPreRecovery   = number
  6711.       from   master.dbo.spt_values
  6712.       where  type                = 'D'
  6713.       and    name                = 'pre recovery'
  6714.  
  6715. SELECT       @DBOptRecovering    = number
  6716.       from   master.dbo.spt_values
  6717.       where  type                = 'D'
  6718.       and    name                = 'recovering'
  6719.  
  6720. SELECT       @DBOptSuspect       = number
  6721.       from   master.dbo.spt_values
  6722.       where  type                = 'D'
  6723.       and    name                = 'not recovered'
  6724.  
  6725. SELECT       @DBOptOffline       = number
  6726.       from   master.dbo.spt_values
  6727.       where  type                = 'D'
  6728.       and    name                = 'offline'
  6729.  
  6730. SELECT       @DBOptDBOUseOnly    = number
  6731.       from   master.dbo.spt_values
  6732.       where  type                = 'D'
  6733.       and    name                = 'dbo use only'
  6734.  
  6735. SELECT       @DBOptSingleUser    = number
  6736.       from   master.dbo.spt_values
  6737.       where  type                = 'D'
  6738.       and    name                = 'single user'
  6739.  
  6740.  
  6741.  
  6742. ---------------  Cursor, for DBNames  -------------------
  6743.  
  6744.  
  6745. DECLARE cursor10_DB
  6746.    Insensitive
  6747.    Cursor For
  6748. SELECT
  6749.              name ,status ,sid
  6750.       from
  6751.              master.dbo.sysdatabases
  6752.  
  6753.  
  6754.  
  6755. OPEN cursor10_DB
  6756.  
  6757.  
  6758. -----------------  LOOP 10:  thru Databases  ------------------
  6759.  
  6760.  
  6761. --------------
  6762. WHILE (10 = 10)
  6763.    begin    --LOOP 10: thru Databases
  6764.  
  6765.  
  6766.    FETCH
  6767.              Next
  6768.       from
  6769.              cursor10_DB
  6770.       into
  6771.              @c10DBName
  6772.             ,@c10DBStatus
  6773.             ,@c10DBSID
  6774.  
  6775.  
  6776.    IF (@@fetch_status <> 0)
  6777.       begin
  6778.       Deallocate cursor10_DB
  6779.       BREAK
  6780.       end
  6781.  
  6782.  
  6783. --------------------  Okay if we peek inside this DB now?
  6784.  
  6785.  
  6786.    IF (     @c10DBStatus & @DBOptDBOUseOnly  > 0
  6787.        AND  @c10DBSID                       <> suser_sid()
  6788.       )
  6789.       begin
  6790.       Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  6791.       CONTINUE
  6792.       end
  6793.  
  6794.  
  6795.    IF (@c10DBStatus & @DBOptSingleUser  > 0)
  6796.       begin
  6797.  
  6798.       SELECT    @Int1 = count(*)
  6799.          from   master.dbo.sysprocesses
  6800.          where  spid <> @@spid
  6801.          and    dbid  = db_id(@c10DBName)
  6802.  
  6803.       IF (@Int1 > 0)
  6804.          begin
  6805.          Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  6806.          CONTINUE
  6807.          end
  6808.       end
  6809.  
  6810.  
  6811.    IF (@c10DBStatus &
  6812.          (
  6813.            @DBOptLoading
  6814.          | @DBOptRecovering
  6815.          | @DBOptSuspect
  6816.          | @DBOptPreRecovery
  6817.          )
  6818.                > 0
  6819.       )
  6820.       begin
  6821.       Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  6822.       CONTINUE
  6823.       end
  6824.  
  6825.  
  6826.    IF (@c10DBStatus &
  6827.          (
  6828.            @DBOptOffline
  6829.          )
  6830.                > 0
  6831.       )
  6832.       begin
  6833.       --Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  6834.       CONTINUE
  6835.       end
  6836.  
  6837.     IF (has_dbaccess(@c10DBName) <> 1)
  6838.       begin
  6839.       raiserror(15622,-1,-1, @c10DBName)
  6840.       CONTINUE
  6841.       end
  6842.  
  6843.  
  6844.  
  6845. ---------------------  Add the User info to holding table.
  6846.     select @exec_stmt = '
  6847.    INSERT    #tb1_UA
  6848.             (
  6849.              DBName
  6850.             ,LoginName
  6851.             ,UserName
  6852.             ,UserOrAlias
  6853.             )
  6854.       Select
  6855.              N' + quotename(@c10DBName, '''') + '
  6856.             ,l.loginname
  6857.             ,u.name
  6858.             ,''User''
  6859.          from
  6860.              ' + quotename(@c10DBName, '[') + '.dbo.sysusers       u
  6861.             ,master.dbo.syslogins                  l
  6862.          where
  6863.              u.sid  = l.sid' +
  6864.             case @LoginNamePattern
  6865.             when null then ''
  6866.             else ' and ( l.name = N' + quotename(@LoginNamePattern , '''') + '
  6867.                 or l.loginname = N' + quotename(@LoginNamePattern , '''') + ')'
  6868.             end
  6869.             +
  6870. '     UNION
  6871.       Select
  6872.  
  6873.              N' + quotename(@c10DBName, '''') + '
  6874.             ,l.loginname
  6875.             ,u2.name
  6876.             ,''MemberOf''
  6877.          from
  6878.              ' + quotename(@c10DBName, '[')+ '.dbo.sysmembers       m
  6879.             ,' + quotename(@c10DBName, '[')+ '.dbo.sysusers       u1
  6880.             ,' + quotename(@c10DBName, '[')+ '.dbo.sysusers       u2
  6881.             ,master.dbo.syslogins                  l
  6882.          where
  6883.              u1.sid     = l.sid
  6884.          and m.memberuid = u1.uid
  6885.          and m.groupuid  = u2.uid' +
  6886.             case @LoginNamePattern
  6887.             when null then ''
  6888.             else ' and ( l.name = N' + quotename(@LoginNamePattern , '''') + '
  6889.                 or l.loginname = N' + quotename(@LoginNamePattern , '''') + ')'
  6890.             end
  6891.   
  6892.    EXECUTE(@exec_stmt)
  6893.  
  6894.    end --loop 10
  6895.  
  6896.  
  6897.  
  6898. ---------------  Populate plain logins work table  ---------------
  6899.  
  6900.  
  6901. INSERT       #tb2_PlainLogins
  6902.             (
  6903.              LoginName
  6904.             ,SID
  6905.             ,DefDBName
  6906.             ,DefLangName
  6907.             ,AUser
  6908.             ,ARemote
  6909.             )
  6910.    SELECT
  6911.              loginname
  6912.             ,convert(varchar(85), sid)
  6913.             ,dbname
  6914.             ,language
  6915.             ,Null
  6916.             ,Null
  6917.       from
  6918.              master.dbo.syslogins
  6919.       where
  6920.              @LoginNamePattern is null
  6921.              or name = @LoginNamePattern
  6922.              or loginname = @LoginNamePattern
  6923.  
  6924.  
  6925. -- AUser
  6926.  
  6927. UPDATE       #tb2_PlainLogins --(1996/08/12)
  6928.       set
  6929.              AUser  = 'yes'
  6930.       from
  6931.              #tb2_PlainLogins
  6932.             ,#tb1_UA             tb1
  6933.       where
  6934.              #tb2_PlainLogins.LoginName     = tb1.LoginName
  6935.       and    #tb2_PlainLogins.AUser        IS Null
  6936.  
  6937.  
  6938.  
  6939. UPDATE       #tb2_PlainLogins
  6940.       set
  6941.              AUser    =
  6942.                   CASE @CountSkipPossUsers
  6943.                      When  0  Then  'NO'
  6944.                      Else           '?'
  6945.                   END
  6946.       where
  6947.              AUser   IS Null
  6948.  
  6949.  
  6950. -- ARemote
  6951.  
  6952. UPDATE       #tb2_PlainLogins
  6953.       set
  6954.              ARemote   = 'YES'
  6955.       from
  6956.              #tb2_PlainLogins
  6957.             ,master.dbo.sysremotelogins   rl
  6958.       where
  6959.              #tb2_PlainLogins.SID = rl.sid
  6960.       and    #tb2_PlainLogins.ARemote                 IS Null
  6961.  
  6962.  
  6963.  
  6964. UPDATE       #tb2_PlainLogins
  6965.       set
  6966.              ARemote  = 'no'
  6967.       where
  6968.              ARemote IS Null
  6969.  
  6970.  
  6971.  
  6972. ------------  Optimize widths for plain Logins report  ----------
  6973.  
  6974.  
  6975. SELECT
  6976.              @charMaxLenLoginName      =
  6977.                   convert ( varchar
  6978.                            ,isnull ( max(datalength(LoginName)) ,9)
  6979.                           )
  6980.             ,@charMaxLenDBName         =
  6981.                   convert ( varchar
  6982.                            ,isnull ( max(datalength(DefDBName)) ,9)
  6983.                           )
  6984.             ,@charMaxLenLangName   =
  6985.                   convert ( varchar
  6986.                            ,isnull ( max(datalength(DefLangName)) ,11)
  6987.                           )
  6988.       from
  6989.              #tb2_PlainLogins
  6990.  
  6991.  
  6992.  
  6993. ----------------  Print out plain Logins report  -------------
  6994.  
  6995. /*** Message Handlers get confused.
  6996. Raiserror('...Logins...' ,0,1)
  6997. ***/
  6998.  
  6999. EXECUTE(
  7000. '
  7001. Set nocount off
  7002.  
  7003.  
  7004. SELECT
  7005.           ''LoginName''       = substring (LoginName     ,1 ,'
  7006.                                        + @charMaxLenLoginName   + ')
  7007.  
  7008.          ,''SID''             = convert(varbinary(85), SID)
  7009.  
  7010.          ,''DefDBName''       = substring (DefDBName     ,1 ,'
  7011.                                        + @charMaxLenDBName      + ')
  7012.  
  7013.          ,''DefLangName''     = substring (DefLangName   ,1 ,'
  7014.                                        + @charMaxLenLangName    + ')
  7015.  
  7016.          ,AUser
  7017.          ,ARemote
  7018.    from
  7019.           #tb2_PlainLogins
  7020.    order by
  7021.           LoginName
  7022.  
  7023.  
  7024. Set nocount on
  7025. '
  7026. )
  7027.  
  7028.  
  7029.  
  7030. ------------  Optimize UA report column display widths  -----------
  7031.  
  7032.  
  7033. SELECT
  7034.              @charMaxLenLoginName   =
  7035.                   convert ( varchar
  7036.                            ,isnull ( max(datalength(LoginName)) ,9)
  7037.                           )
  7038.             ,@charMaxLenDBName      =
  7039.                   convert ( varchar
  7040.                            ,isnull ( max(datalength(DBName)) ,6)
  7041.                           )
  7042.             ,@charMaxLenUserName    =
  7043.                   convert ( varchar
  7044.                            ,isnull ( max(datalength(UserName)) ,8)
  7045.                           )
  7046.       from
  7047.              #tb1_UA
  7048.  
  7049.  
  7050.  
  7051. ------------  Print out the UserOrAlias report  ------------
  7052.  
  7053. /***
  7054. Raiserror('...Logins-to-Users...' ,0,1)
  7055. ***/
  7056.  
  7057. EXECUTE(
  7058. '
  7059. Set nocount off
  7060.  
  7061.  
  7062. SELECT
  7063.           ''LoginName''    = substring (LoginName  ,1 ,'
  7064.                                        + @charMaxLenLoginName  + ')
  7065.  
  7066.          ,''DBName''       = substring (DBName     ,1 ,'
  7067.                                        + @charMaxLenDBName     + ')
  7068.  
  7069.          ,''UserName''     = substring (UserName   ,1 ,'
  7070.                                        + @charMaxLenUserName   + ')
  7071.  
  7072.          ,UserOrAlias
  7073.    from
  7074.           #tb1_UA
  7075.    order by
  7076.           1 ,2 ,3
  7077.  
  7078.  
  7079. Set nocount on
  7080. '
  7081. )
  7082.  
  7083.  
  7084. -----------------------  Finalization  --------------------
  7085. label_86return:
  7086.  
  7087. IF (object_id('#tb2_PlainLogins') IS NOT Null)
  7088.             DROP Table #tb2_PlainLogins
  7089.  
  7090. IF (object_id('#tb1_UA') IS NOT Null)
  7091.             DROP Table #tb1_UA
  7092.  
  7093. Return @RetCode -- sp_helplogins
  7094. go
  7095.  
  7096.  
  7097. raiserror(15339,-1,-1,'sp_helpindex')
  7098. go
  7099. create proc sp_helpindex
  7100.     @objname nvarchar(776)        -- the table to check for indexes
  7101. as
  7102.     -- PRELIM
  7103.     set nocount on
  7104.  
  7105.     declare @objid int,            -- the object id of the table
  7106.             @indid smallint,    -- the index id of an index
  7107.             @groupid smallint,  -- the filegroup id of an index
  7108.             @indname sysname,
  7109.             @groupname sysname,
  7110.             @status int,
  7111.             @keys nvarchar(2078),-- string build index key list, length = (16*max_id_length)+(15*2)
  7112.             @dbname    sysname
  7113.  
  7114.     -- Check to see that the object names are local to the current database.
  7115.     select @dbname = parsename(@objname,3) 
  7116.  
  7117.     if @dbname is not null and @dbname <> db_name()
  7118.     begin
  7119.             raiserror(15250,-1,-1)
  7120.             return (1)
  7121.     end
  7122.  
  7123.     -- Check to see the the table exists and initialize @objid.
  7124.     select @objid = object_id(@objname)
  7125.     if @objid is NULL
  7126.     begin
  7127.         select @dbname=db_name()
  7128.         raiserror(15009,-1,-1,@objname,@dbname)
  7129.         return (1)
  7130.     end
  7131.  
  7132.     -- OPEN CURSOR OVER INDEXES
  7133.     declare ind_curs insensitive cursor for
  7134.         select indid, groupid, name, status from sysindexes
  7135.             where id = @objid and indid > 0 and indid < 255 order by indid
  7136.     open ind_curs
  7137.     fetch ind_curs into @indid, @groupid, @indname, @status
  7138.  
  7139.     -- IF NO INDEX, QUIT
  7140.     if @@fetch_status < 0
  7141.     begin
  7142.         deallocate ind_curs
  7143.         raiserror(15472,-1,-1) --'Object does not have any indexes.'
  7144.         return (0)
  7145.     end
  7146.  
  7147.     -- create temp table
  7148.     create table #spindtab
  7149.     (
  7150.         index_name            sysname    NOT NULL,
  7151.         stats                int,
  7152.         groupname            sysname NOT NULL,
  7153.         index_keys            nvarchar(2078)    NOT NULL
  7154.     )
  7155.  
  7156.     -- Now check out each index, figure out its type and keys and
  7157.     --    save the info in a temporary table that we'll print out at the end.
  7158.     while @@fetch_status >= 0
  7159.     begin
  7160.         -- First we'll figure out what the keys are.
  7161.         declare @i int, @thiskey sysname
  7162.         select @keys = index_col(@objname, @indid, 1),
  7163.                 @i = 2, @thiskey = index_col(@objname, @indid, 2)
  7164.         while (@thiskey is not null )
  7165.         begin
  7166.             select @keys = @keys + ', ' + @thiskey, @i = @i + 1
  7167.             select @thiskey = index_col(@objname, @indid, @i)
  7168.         end
  7169.  
  7170.         select @groupname = groupname from sysfilegroups where groupid = @groupid
  7171.  
  7172.         -- INSERT ROW FOR INDEX
  7173.         insert into #spindtab values (@indname, @status, @groupname, @keys)
  7174.  
  7175.         -- Next index
  7176.         fetch ind_curs into @indid, @groupid, @indname, @status
  7177.     end
  7178.     deallocate ind_curs
  7179.  
  7180.     -- SET UP SOME CONSTANT VALUES FOR OUTPUT QUERY
  7181.     declare @empty varchar(1) select @empty = ''
  7182.     declare @des1            varchar(35),    -- 35 matches spt_values
  7183.             @des2            varchar(35),
  7184.             @des4            varchar(35),
  7185.             @des32            varchar(35),
  7186.             @des64            varchar(35),
  7187.             @des2048        varchar(35),
  7188.             @des4096        varchar(35),
  7189.             @des8388608        varchar(35),
  7190.             @des16777216    varchar(35)
  7191.     select @des1 = name from master.dbo.spt_values where type = 'I' and number = 1
  7192.     select @des2 = name from master.dbo.spt_values where type = 'I' and number = 2
  7193.     select @des4 = name from master.dbo.spt_values where type = 'I' and number = 4
  7194.     select @des32 = name from master.dbo.spt_values where type = 'I' and number = 32
  7195.     select @des64 = name from master.dbo.spt_values where type = 'I' and number = 64
  7196.     select @des2048 = name from master.dbo.spt_values where type = 'I' and number = 2048
  7197.     select @des4096 = name from master.dbo.spt_values where type = 'I' and number = 4096
  7198.     select @des8388608 = name from master.dbo.spt_values where type = 'I' and number = 8388608
  7199.     select @des16777216 = name from master.dbo.spt_values where type = 'I' and number = 16777216
  7200.  
  7201.     -- DISPLAY THE RESULTS
  7202.     select
  7203.         'index_name' = index_name,
  7204.         'index_description' = convert(varchar(210), --bits 16 off, 1, 2, 16777216 on, located on group
  7205.                 case when (stats & 16)<>0 then 'clustered' else 'nonclustered' end 
  7206.                 + case when (stats & 1)<>0 then ', '+@des1 else @empty end
  7207.                 + case when (stats & 2)<>0 then ', '+@des2 else @empty end
  7208.                 + case when (stats & 4)<>0 then ', '+@des4 else @empty end
  7209.                 + case when (stats & 64)<>0 then ', '+@des64 else case when (stats & 32)<>0 then ', '+@des32 else @empty end end
  7210.                 + case when (stats & 2048)<>0 then ', '+@des2048 else @empty end
  7211.                 + case when (stats & 4096)<>0 then ', '+@des4096 else @empty end
  7212.                 + case when (stats & 8388608)<>0 then ', '+@des8388608 else @empty end
  7213.                 + case when (stats & 16777216)<>0 then ', '+@des16777216 else @empty end
  7214.                 + ' located on ' + groupname),
  7215.         'index_keys' = index_keys
  7216.     from #spindtab
  7217.  
  7218.  
  7219.     return (0) -- sp_helpindex
  7220. go
  7221.  
  7222. raiserror(15339,-1,-1,'sp_objectfilegroup')
  7223. go
  7224. create procedure sp_objectfilegroup --- 1996/08/30 17:44
  7225. @objid    int
  7226. as
  7227.     /*
  7228.     ** Print out the object's data filegroup if applicable.
  7229.     */
  7230.     if exists (select * from sysobjects
  7231.             where id = @objid
  7232.             and type in ('S ','U '))
  7233.         begin
  7234.             select Data_located_on_filegroup = s.groupname
  7235.             from sysfilegroups s, sysindexes i
  7236.             where i.id = @objid
  7237.                 and i.indid < 2
  7238.                 and i.groupid = s.groupid
  7239.         end
  7240.  
  7241.     /*
  7242.     **  It's not a table so segment is not applicable.
  7243.     */
  7244.     else
  7245.         select Data_located_on_filegroup = 'not applicable'
  7246.  
  7247. return (0) -- sp_objectfilegroup
  7248. go
  7249.  
  7250. raiserror(15339,-1,-1,'sp_help')
  7251. go
  7252. create proc sp_help
  7253.     @objname nvarchar(776) = NULL        -- object name we're after
  7254. as
  7255.     -- PRELIMINARY
  7256.     set nocount on
  7257.     declare    @dbname    sysname
  7258.  
  7259.     -- OBTAIN DISPLAY STRINGS FROM spt_values UP FRONT --
  7260.     declare @no varchar(35), @yes varchar(35), @none varchar(35)
  7261.     select @no = name from master.dbo.spt_values where type = 'B' and number = 0
  7262.     select @yes = name from master.dbo.spt_values where type = 'B' and number = 1
  7263.     select @none = name from master.dbo.spt_values where type = 'B' and number = 2
  7264.  
  7265.     -- If no @objname given, give a little info about all objects.
  7266.     if @objname is null
  7267.     begin
  7268.         -- DISPLAY ALL SYSOBJECTS --
  7269.         select
  7270.             'Name'            = o.name,
  7271.             'Owner'            = user_name(uid),
  7272.             'Object_type'    = substring(v.name,5,31)
  7273.         from sysobjects o, master.dbo.spt_values v
  7274.         where o.xtype = substring(v.name,1,2) and v.type = 'O9T'
  7275.         order by Object_type desc, Name asc
  7276.  
  7277.         print ' '
  7278.  
  7279.         -- DISPLAY ALL USER TYPES
  7280.         select
  7281.             'User_type'        = name,
  7282.             'Storage_type'    = type_name(xtype),
  7283.             'Length'        = length,
  7284.             'Prec'            = TypeProperty(name, 'precision'),
  7285.             'Scale'            = TypeProperty(name, 'scale'),
  7286.             'Nullable'        = case when TypeProperty(name, 'AllowsNull') = 1
  7287.                                             then @yes else @no end,
  7288.             'Default_name'    = isnull(object_name(tdefault), @none),
  7289.             'Rule_name'        = isnull(object_name(domain), @none)
  7290.         from systypes
  7291.         where xusertype > 256
  7292.         order by name
  7293.  
  7294.         return(0)
  7295.     end
  7296.  
  7297.     -- Make sure the @objname is local to the current database.
  7298.     select @dbname = parsename(@objname,3) 
  7299.  
  7300.     if @dbname is not null and @dbname <> db_name()
  7301.         begin
  7302.             raiserror(15250,-1,-1)
  7303.             return(1)
  7304.         end
  7305.  
  7306.     -- @objname must be either sysobjects or systypes: first look in sysobjects
  7307.     declare @objid int
  7308.     declare @sysobj_type char(2)
  7309.     select @objid = id, @sysobj_type = xtype from sysobjects where id = object_id(@objname)
  7310.  
  7311.     -- IF NOT IN SYSOBJECTS, TRY SYSTYPES --
  7312.     if @objid is null
  7313.     begin
  7314.         -- UNDONE: SHOULD CHECK FOR AND DISALLOW MULTI-PART NAME
  7315.         select @objid = xusertype from systypes where name = @objname
  7316.  
  7317.         -- IF NOT IN SYSTYPES, GIVE UP
  7318.         if @objid is null
  7319.         begin
  7320.             select @dbname=db_name()
  7321.             raiserror(15009,-1,-1,@objname,@dbname)
  7322.             return(1)
  7323.         end
  7324.  
  7325.         -- DATA TYPE HELP (prec/scale only valid for numerics)
  7326.         select
  7327.             'Type_name'        = name,
  7328.             'Storage_type'    = type_name(xtype),
  7329.             'Length'        = length,
  7330.             'Prec'            = TypeProperty(name, 'precision'),
  7331.             'Scale'            = TypeProperty(name, 'scale'),
  7332.             'Nullable'        = case when allownulls=1 then @yes else @no end,
  7333.             'Default_name'    = isnull(object_name(tdefault), @none),
  7334.             'Rule_name'        = isnull(object_name(domain), @none)
  7335.         from systypes
  7336.         where xusertype = @objid
  7337.  
  7338.         return(0)
  7339.     end
  7340.  
  7341.     -- FOUND IT IN SYSOBJECT, SO GIVE OBJECT INFO
  7342.     select
  7343.         'Name'                = o.name,
  7344.         'Owner'                = user_name(uid),
  7345.         'Type'                = substring(v.name,5,31),
  7346.         'Created_datetime'    = o.crdate
  7347.     from sysobjects o, master.dbo.spt_values v
  7348.     where o.id = @objid and o.xtype  = substring(v.name,1,2) and v.type = 'O9T'
  7349.  
  7350.     print ' '
  7351.  
  7352.     -- DISPLAY COLUMN IF TABLE / VIEW
  7353.     if @sysobj_type in ('S ','U ','V ')
  7354.     begin
  7355.  
  7356.         -- SET UP NUMERIC TYPES: THESE WILL HAVE NON-BLANK PREC/SCALE
  7357.         declare @numtypes nvarchar(80)
  7358.         select @numtypes = N'tinyint,smallint,decimal,int,real,money,float,numeric,smallmoney'
  7359.  
  7360.         -- INFO FOR EACH COLUMN
  7361.         print ' '
  7362.         select
  7363.             'Column_name'            = name,
  7364.             'Type'                    = type_name(xusertype),
  7365.             'Computed'                = case when iscomputed = 0 then @no else @yes end,
  7366.             'Length'                = convert(int, length),
  7367.             'Prec'                    = case when charindex(type_name(xtype), @numtypes) > 0
  7368.                                         then convert(char(5),ColumnProperty(id, name, 'precision'))
  7369.                                         else '     ' end,
  7370.             'Scale'                    = case when charindex(type_name(xtype), @numtypes) > 0
  7371.                                         then convert(char(5),OdbcScale(xtype,xscale))
  7372.                                         else '     ' end,
  7373.             'Nullable'                = case when isnullable = 0 then @no else @yes end,
  7374.             'TrimTrailingBlanks'    = case ColumnProperty(@objid, name, 'UsesAnsiTrim')
  7375.                                         when 1 then @no
  7376.                                         when 0 then @yes
  7377.                                         else '(n/a)' end,
  7378.             'FixedLenNullInSource'    = case
  7379.                         when type_name(xtype) not in ('varbinary','varchar','binary','char')
  7380.                             Then '(n/a)'
  7381.                         When status & 0x20 = 0 Then @no
  7382.                         Else @yes END
  7383.         from syscolumns where id = @objid order by colid
  7384.  
  7385.         -- IDENTITY COLUMN?
  7386.         print ' '
  7387.         declare @colname sysname
  7388.         select @colname = name from syscolumns where id = @objid
  7389.                     and colstat & 1 = 1
  7390.         select
  7391.             'Identity'                = isnull(@colname,'No identity column defined.'),
  7392.             'Seed'                    = ident_seed(@objname),
  7393.             'Increment'                = ident_incr(@objname),
  7394.             'Not For Replication'    = ColumnProperty(@objid, @colname, 'IsIDNotForRepl')
  7395.  
  7396.         -- ROWGUIDCOL?
  7397.         print ' '
  7398.         select @colname = null
  7399.         select @colname = name from syscolumns where id = @objid
  7400.                     and ColumnProperty(@objid, name, 'IsRowGuidCol') = 1
  7401.         select 'RowGuidCol' = isnull(@colname,'No rowguidcol column defined.')
  7402.  
  7403.     end
  7404.  
  7405.     -- DISPLAY PROC PARAMS
  7406.     if @sysobj_type in ('P ') --RF too?
  7407.     begin
  7408.         -- ANY PARAMS FOR THIS PROC?
  7409.         if exists (select id from syscolumns where id = @objid)
  7410.         begin
  7411.             -- INFO ON PROC PARAMS
  7412.             print ' '
  7413.             select
  7414.                 'Parameter_name'    = name,
  7415.                 'Type'                = type_name(xusertype),
  7416.                 'Length'            = length,
  7417.                 'Prec'                = case when type_name(xtype) = 'uniqueidentifier' then xprec
  7418.                                         else OdbcPrec(xtype, length, xprec) end, 
  7419.                 'Scale'                = OdbcScale(xtype,xscale),
  7420.                 'Param_order'        = colid
  7421.             from syscolumns where id = @objid
  7422.         end
  7423.     end
  7424.  
  7425.     -- DISPLAY TABLE INDEXES & CONSTRAINTS
  7426.     if @sysobj_type in ('S ','U ')
  7427.     begin
  7428.         print ' '
  7429.         execute sp_objectfilegroup @objid
  7430.         print ' '
  7431.         execute sp_helpindex @objname
  7432.         print ' '
  7433.         execute sp_helpconstraint @objname,'nomsg'
  7434.     end
  7435.     else if @sysobj_type in ('V ')
  7436.     begin
  7437.         -- VIEWS DONT HAVE CONSTRAINTS, BUT PRINT THESE MESSAGES BECAUSE 6.5 DID
  7438.         print ' '
  7439.         raiserror(15469,-1,-1) -- No constraints defined
  7440.         print ' '
  7441.         raiserror(15470,-1,-1) --'No foreign keys reference this table.'
  7442.     end
  7443.  
  7444.     return (0) -- sp_help
  7445. go
  7446.  
  7447. checkpoint
  7448. go
  7449.  
  7450.  
  7451. raiserror(15339,-1,-1,'sp_helprotect')
  7452. go
  7453. CREATE PROCEDURE sp_helprotect
  7454.     @name                ncharacter varying(776)  = NULL
  7455.     ,@username            sysname  = NULL
  7456.     ,@grantorname        sysname  = NULL
  7457.     ,@permissionarea    character varying(10)  = 'o s'
  7458. as
  7459.  
  7460. /********
  7461. Explanation of the parms...
  7462. ---------------------------
  7463. @name:  Name of [Owner.]Object and Statement; meaning
  7464. for sysprotects.id and sysprotects.action at the
  7465. same time; thus see parm @permissionarea.
  7466.    Examples-   'user2.tb'  , 'CREATE TABLE', null
  7467.  
  7468. @username:  Name of the grantee (for sysprotects.uid).
  7469.    Examples-   'user2', null
  7470.  
  7471. @grantorname:  Name of the grantor (for sysprotects.grantor).
  7472.    Examples-   'user2' --Would prevent report rows which would
  7473.                        --  have 'dbo' as grantor.
  7474.  
  7475. @permissionarea:  O=Object, S=Statement; include all which apply.
  7476.    Examples-   'o'  , ',s'  , 'os'  , 'so'  , 's o'  , 's,o'
  7477. GeneMi
  7478. ********/
  7479.  
  7480.     Set nocount on
  7481.  
  7482.     Declare    
  7483.     @vc1                   sysname
  7484.     ,@Int1                  integer
  7485.  
  7486.     Declare    
  7487.     @charMaxLenOwner        character varying(11)
  7488.     ,@charMaxLenObject        character varying(11)
  7489.     ,@charMaxLenGrantee        character varying(11)
  7490.     ,@charMaxLenGrantor        character varying(11)
  7491.     ,@charMaxLenAction        character varying(11)
  7492.     ,@charMaxLenColumnName    character varying(11)
  7493.  
  7494.     Declare
  7495.     @OwnerName                sysname
  7496.     ,@ObjectStatementName    sysname
  7497.  
  7498.  
  7499.     /* Perform temp table DDL here to minimize compilation costs*/
  7500. CREATE Table #t1_Prots
  7501.     (    Id                    int                Null
  7502.         ,Type1Code            char(6)            NOT Null
  7503.         ,ObjType            char(2)            Null
  7504.  
  7505.         ,ActionName        varchar(20)            Null
  7506.         ,ActionCategory    char(2)                Null        
  7507.         ,ProtectTypeName    char(10)        Null
  7508.  
  7509.         ,Columns_Orig        varbinary(32)    Null    
  7510.  
  7511.         ,OwnerName            sysname            NOT Null
  7512.         ,ObjectName            sysname            NOT Null
  7513.         ,GranteeName        sysname            NOT Null
  7514.         ,GrantorName        sysname            NOT Null
  7515.  
  7516.         ,ColumnName            sysname            Null
  7517.         ,ColId                smallint        Null
  7518.  
  7519.         ,Max_ColId            smallint        Null
  7520.         ,All_Col_Bits_On    tinyint            Null
  7521.         ,new_Bit_On            tinyint            Null )  -- 1=yes on
  7522.  
  7523.  
  7524.     /*    Check for valid @permissionarea */
  7525.     Select @permissionarea = upper( isnull(@permissionarea,'?') )
  7526.  
  7527.     IF (    charindex('O',@permissionarea) <= 0 
  7528.         AND  charindex('S',@permissionarea) <= 0)
  7529.     begin
  7530.         raiserror(15300,-1,-1 ,@permissionarea,'o,s')
  7531.         return (1)
  7532.     end
  7533.  
  7534.     select @vc1 = parsename(@name,3) 
  7535.  
  7536.     /* Verified db qualifier is current db*/
  7537.     IF (@vc1 is not null and @vc1 <> db_name())
  7538.     begin
  7539.         raiserror(15302,-1,-1)  --Do not qualify with DB name.
  7540.         return (1)
  7541.     end
  7542.  
  7543.     /*  Derive OwnerName and @ObjectStatementName*/
  7544.     select    @OwnerName                =    parsename(@name, 2)
  7545.             ,@ObjectStatementName    =    parsename(@name, 1)
  7546.  
  7547.     IF (@ObjectStatementName is NULL and @name is not null)
  7548.     begin
  7549.         raiserror(15253,-1,-1,@name)
  7550.         return (1)
  7551.     end
  7552.  
  7553.     /*    Copy info from sysprotects for processing    */
  7554.     IF charindex('O',@permissionarea) > 0
  7555.     begin 
  7556.         /*    Copy info for objects    */
  7557.         INSERT    #t1_Prots
  7558.         (    Id
  7559.             ,Type1Code
  7560.  
  7561.             ,ObjType
  7562.             ,ActionName
  7563.             ,ActionCategory
  7564.             ,ProtectTypeName
  7565.  
  7566.             ,Columns_Orig
  7567.             ,OwnerName
  7568.             ,ObjectName
  7569.             ,GranteeName
  7570.  
  7571.             ,GrantorName
  7572.             ,ColumnName
  7573.             ,ColId
  7574.  
  7575.             ,Max_ColId
  7576.             ,All_Col_Bits_On
  7577.             ,new_Bit_On    )
  7578.  
  7579.     /*    1Regul indicates action can be at column level, 
  7580.         2Simpl indicates action is at the object level */
  7581.         SELECT    id
  7582.                 ,case 
  7583.                     when columns is null then '2Simpl'
  7584.                     else '1Regul'
  7585.                 end
  7586.  
  7587.                 ,Null
  7588.                 ,val1.name
  7589.                 ,'Ob'
  7590.                 ,val2.name
  7591.  
  7592.                 ,columns
  7593.                 ,user_name(objectproperty( id, 'ownerid' ))
  7594.                 ,object_name(id)
  7595.                 ,user_name(uid)
  7596.  
  7597.                 ,user_name(grantor)
  7598.                 ,case 
  7599.                     when columns is null then '.'
  7600.                     else Null
  7601.                 end
  7602.                 ,-123
  7603.  
  7604.                 ,Null
  7605.                 ,Null
  7606.                 ,Null
  7607.         FROM    sysprotects sysp
  7608.                 ,master.dbo.spt_values  val1
  7609.                 ,master.dbo.spt_values  val2
  7610.         where    (@OwnerName is null or user_name(objectproperty( id, 'ownerid' )) = @OwnerName)
  7611.         and    (@ObjectStatementName is null or object_name(id) =  @ObjectStatementName)
  7612.         and    (@username is null or user_name(uid) =  @username)
  7613.         and    (@grantorname is null or user_name(grantor) =  @grantorname)
  7614.         and    val1.type     = 'T'
  7615.         and    val1.number   = sysp.action
  7616.         and    val2.type     = 'T' --T is overloaded.    
  7617.         and    val2.number   = sysp.protecttype
  7618.         and sysp.id != 0
  7619.  
  7620.  
  7621.         IF EXISTS (SELECT * From #t1_Prots)
  7622.         begin
  7623.             UPDATE    #t1_Prots set ObjType = ob.xtype
  7624.             FROM    sysobjects    ob
  7625.             WHERE    ob.id    =  #t1_Prots.Id
  7626.         
  7627.  
  7628.             UPDATE     #t1_Prots 
  7629.             set        Max_ColId = (select count(*) from syscolumns sysc
  7630.                                 where #t1_Prots.Id = sysc.id)
  7631.             where Type1Code = '1Regul'
  7632.  
  7633.  
  7634.             /*    First bit set indicates actions pretains to new columns. 
  7635.                 Set new_Bit_On accordinglly                            */
  7636.             UPDATE    #t1_Prots SET new_Bit_On = 
  7637.             CASE    convert(int,substring(Columns_Orig,1,1)) & 1 
  7638.                 WHEN    1 then    1
  7639.                 ELSE    0
  7640.             END
  7641.             WHERE    ObjType    <> 'V'    and     Type1Code = '1Regul'
  7642.  
  7643.  
  7644.             /* Views don't get new columns    */
  7645.             UPDATE #t1_Prots set new_Bit_On = 0
  7646.             WHERE  ObjType = 'V'
  7647.  
  7648.  
  7649.             /*    Indicate enties where column level action pretains to all 
  7650.                 columns in table All_Col_Bits_On = 1                    */
  7651.             UPDATE    #t1_Prots    set        All_Col_Bits_On = 1 
  7652.             where    #t1_Prots.Type1Code     =  '1Regul'
  7653.             and    Max_ColId = 
  7654.                 (select count(*) 
  7655.                 from syscolumns sysc, master..spt_values v
  7656.                 where #t1_Prots.Id = sysc.id and sysc.colid = v.number
  7657.                 and v.number <= Max_ColId
  7658.                 and v.type = 'P' and
  7659.             /*    Columns_Orig where first byte is 1 means off means on and on mean off
  7660.                 where first byte is 0 means off means off and on mean on    */ 
  7661.                     case convert(int,substring(#t1_Prots.Columns_Orig, 1, 1)) & 1
  7662.                         when 0 then convert(tinyint, substring(#t1_Prots.Columns_Orig, v.low, 1))
  7663.                         else (~convert(tinyint, isnull(substring(#t1_Prots.Columns_Orig, v.low, 1),0)))
  7664.                     end & v.high <> 0) 
  7665.  
  7666.  
  7667.             /* Indicate entries where column level action pretains to 
  7668.                 only some of columns in table  All_Col_Bits_On  =  0*/
  7669.             UPDATE    #t1_Prots    set  All_Col_Bits_On  =  0 
  7670.             WHERE    #t1_Prots.Type1Code  =  '1Regul'
  7671.             and    All_Col_Bits_On  is  null
  7672.             
  7673.  
  7674.             Update #t1_Prots    
  7675.             set ColumnName  = 
  7676.             case 
  7677.                 when All_Col_Bits_On = 1 and new_Bit_On = 1 then '(All+New)'
  7678.                 when All_Col_Bits_On = 1 and new_Bit_On = 0 then '(All)'
  7679.                 when All_Col_Bits_On = 0 and new_Bit_On = 1 then '(New)'
  7680.             end
  7681.             from    #t1_Prots
  7682.             where    ObjType    IN ('S ' ,'U ', 'V ')
  7683.             and    Type1Code = '1Regul'
  7684.             and   NOT (All_Col_Bits_On = 0 and new_Bit_On = 0)
  7685.  
  7686.  
  7687.             /* Expand and Insert individual column permission rows */
  7688.             INSERT    into   #t1_Prots
  7689.                 (Id                
  7690.                 ,Type1Code
  7691.                 ,ObjType
  7692.                 ,ActionName
  7693.  
  7694.                 ,ActionCategory
  7695.                 ,ProtectTypeName
  7696.                 ,OwnerName
  7697.                 ,ObjectName    
  7698.  
  7699.                 ,GranteeName
  7700.                 ,GrantorName
  7701.                 ,ColumnName    
  7702.                 ,ColId    )
  7703.            SELECT    Id                
  7704.                     ,'1Regul'
  7705.                     ,ObjType
  7706.                     ,ActionName
  7707.  
  7708.                     ,ActionCategory
  7709.                     ,ProtectTypeName
  7710.                     ,OwnerName
  7711.                     ,ObjectName    
  7712.  
  7713.                     ,GranteeName
  7714.                     ,GrantorName
  7715.                     ,col_name ( prot1.Id ,val1.number )
  7716.                     ,val1.number
  7717.             from    #t1_Prots              prot1
  7718.                     ,master.dbo.spt_values  val1
  7719.             where    prot1.ObjType    IN ('S ' ,'U ' ,'V ')
  7720.                 and    prot1.All_Col_Bits_On = 0
  7721.                 and    val1.type        = 'P'
  7722.                 and    val1.number BETWEEN 1 AND prot1.Max_ColId
  7723.                 and    
  7724.                 case convert(int,substring(prot1.Columns_Orig, 1, 1)) & 1
  7725.                     when 0 then convert(tinyint, substring(prot1.Columns_Orig, val1.low, 1))
  7726.                     else (~convert(tinyint, isnull(substring(prot1.Columns_Orig, val1.low, 1),0)))
  7727.                 end & val1.high <> 0
  7728.  
  7729.             delete from #t1_Prots
  7730.                     where    ObjType    IN ('S ' ,'U ' ,'V ')
  7731.                             and    All_Col_Bits_On = 0
  7732.                             and new_Bit_On = 0
  7733.         end
  7734.     end
  7735.  
  7736.  
  7737.     /* Handle statement permissions here*/
  7738.     IF (charindex('S',@permissionarea) > 0)
  7739.     begin
  7740.        /*    All statement permissions are 2Simpl */
  7741.         INSERT    #t1_Prots
  7742.              (    Id
  7743.                 ,Type1Code
  7744.                 ,ObjType
  7745.                 ,ActionName
  7746.  
  7747.                 ,ActionCategory
  7748.                 ,ProtectTypeName
  7749.                 ,Columns_Orig
  7750.                 ,OwnerName
  7751.  
  7752.                 ,ObjectName
  7753.                 ,GranteeName
  7754.                 ,GrantorName
  7755.                 ,ColumnName
  7756.  
  7757.                 ,ColId
  7758.                 ,Max_ColId
  7759.                 ,All_Col_Bits_On
  7760.                 ,new_Bit_On    )
  7761.         SELECT    id
  7762.                 ,'2Simpl'
  7763.                 ,Null
  7764.                 ,val1.name
  7765.  
  7766.                 ,'St'
  7767.                 ,val2.name
  7768.                 ,columns
  7769.                 ,'.'
  7770.  
  7771.                 ,'.'
  7772.                 ,user_name(sysp.uid)
  7773.                 ,user_name(sysp.grantor)
  7774.                 ,'.'
  7775.                 ,-123
  7776.  
  7777.                 ,Null
  7778.                 ,Null
  7779.                 ,Null
  7780.         FROM    sysprotects                sysp
  7781.                 ,master.dbo.spt_values    val1
  7782.                 ,master.dbo.spt_values  val2
  7783.         where    (@username is null or user_name(sysp.uid) = @username)
  7784.             and    (@grantorname is null or user_name(sysp.grantor) = @grantorname)
  7785.             and    val1.type     = 'T'
  7786.             and    val1.number   =  sysp.action
  7787.             and    (@ObjectStatementName is null or val1.name = @ObjectStatementName)
  7788.             and    val2.number   = sysp.protecttype
  7789.             and    val2.type     = 'T'
  7790.             and sysp.id = 0
  7791.     end
  7792.  
  7793.  
  7794.     IF NOT EXISTS (SELECT * From #t1_Prots)
  7795.     begin
  7796.         raiserror(15330,-1,-1)
  7797.         return (1)
  7798.     end
  7799.  
  7800.  
  7801.     /*    Calculate dynamic display col widths        */
  7802.     SELECT
  7803.     @charMaxLenOwner       =
  7804.         convert ( varchar, max(datalength(OwnerName)))
  7805.  
  7806.     ,@charMaxLenObject      =
  7807.         convert ( varchar, max(datalength(ObjectName)))
  7808.  
  7809.     ,@charMaxLenGrantee     =
  7810.         convert ( varchar, max(datalength(GranteeName)))
  7811.  
  7812.     ,@charMaxLenGrantor     =
  7813.         convert ( varchar, max(datalength(GrantorName)))
  7814.  
  7815.     ,@charMaxLenAction      =
  7816.         convert ( varchar, max(datalength(ActionName)))
  7817.  
  7818.     ,@charMaxLenColumnName  =
  7819.         convert ( varchar, max(datalength(ColumnName)))
  7820.     from    #t1_Prots
  7821.  
  7822.  
  7823. /*  Output the report    */
  7824. EXECUTE(
  7825. 'Set nocount off
  7826.  
  7827. SELECT    ''Owner''        = substring (OwnerName   ,1 ,' + @charMaxLenOwner   + ')
  7828.  
  7829.         ,''Object''        = substring (ObjectName  ,1 ,' + @charMaxLenObject  + ')
  7830.  
  7831.         ,''Grantee''    = substring (GranteeName ,1 ,' + @charMaxLenGrantee + ')
  7832.  
  7833.         ,''Grantor''    = substring (GrantorName ,1 ,' + @charMaxLenGrantor + ')
  7834.  
  7835.         ,''ProtectType''= ProtectTypeName
  7836.  
  7837.         ,''Action''        = substring (ActionName ,1 ,' + @charMaxLenAction + ')
  7838.  
  7839.         ,''Column''        = substring (ColumnName ,1 ,' + @charMaxLenColumnName + ')
  7840.    from    #t1_Prots
  7841.    order by
  7842.         ActionCategory
  7843.         ,Owner                ,Object
  7844.         ,Grantee            ,Grantor
  7845.         ,ProtectType        ,Action
  7846.         ,ColId  --Multiple  -123s  ( <0 )  possible
  7847.  
  7848. Set nocount on'
  7849. )
  7850.  
  7851. Return (0) -- sp_helprotect
  7852. go
  7853.  
  7854. checkpoint
  7855. go
  7856.  
  7857. raiserror(15339,-1,-1,'sp_helptext')
  7858. go
  7859. create procedure sp_helptext --- 1996/04/08 00:00
  7860. @objname nvarchar(776)
  7861. as
  7862.  
  7863. set nocount on
  7864.  
  7865. declare @dbname sysname
  7866. ,@BlankSpaceAdded    int
  7867. ,@BasePos        int
  7868. ,@CurrentPos    int
  7869. ,@TextLength    int 
  7870. ,@LineId        int
  7871. ,@AddOnLen        int
  7872. ,@LFCR            int --lengths of line feed carriage return
  7873. ,@DefinedLength    int
  7874. /* NOTE: Length of @SyscomText is 4000 to replace the length of
  7875. ** text column in syscomments. 
  7876.  
  7877. ** lengths on @Line, #CommentText Text column and
  7878. ** value for @DefinedLength are all 255. These need to all have
  7879. ** the same values. 255 was selected in order for the max length
  7880. ** display using down level clients
  7881. */
  7882. ,@SyscomText    nvarchar(4000)
  7883. ,@Line            nvarchar(255)
  7884.  
  7885. Select @DefinedLength = 255
  7886. SELECT @BlankSpaceAdded = 0 /*Keeps track of blank spaces at end of lines. Note Len function ignores
  7887.                              trailing blank spaces*/
  7888.  
  7889. CREATE TABLE #CommentText
  7890. (LineId    int
  7891.  ,Text  nvarchar(255))
  7892.  
  7893. /*
  7894. **  Make sure the @objname is local to the current database.
  7895. */
  7896. select @dbname = parsename(@objname,3)
  7897.  
  7898. if @dbname is not null and @dbname <> db_name()
  7899.         begin
  7900.                 raiserror(15250,-1,-1)
  7901.                 return (1)
  7902.         end
  7903.  
  7904. /*
  7905. **  See if @objname exists.
  7906. */
  7907. if (object_id(@objname) is null)
  7908.         begin
  7909.         select @dbname = db_name()
  7910.         raiserror(15009,-1,-1,@objname,@dbname)
  7911.                 return (1)
  7912.         end
  7913.  
  7914. /*
  7915. **  Find out how many lines of text are coming back,
  7916. **  and return if there are none.
  7917. */
  7918. if (select count(*) from syscomments c, sysobjects o where o.xtype not in ('S', 'U')
  7919.     and o.id = c.id and o.id = object_id(@objname)) = 0 
  7920.         begin
  7921.                 raiserror(15197,-1,-1,@objname)
  7922.                 return (1)
  7923.         end
  7924.  
  7925. if (select count(*) from syscomments where id = object_id(@objname)
  7926.     and encrypted = 0) = 0
  7927.         begin
  7928.                 raiserror(15471,-1,-1)
  7929.                 return (0)
  7930.         end
  7931.  
  7932. /*
  7933. **  Else get the text.
  7934. */
  7935. SELECT @LFCR = 2
  7936. SELECT @LineId = 1
  7937.  
  7938. DECLARE SysComCursor  CURSOR
  7939. FOR SELECT text FROM syscomments WHERE id = OBJECT_ID(@objname) and encrypted = 0 ORDER BY number, colid
  7940. FOR READ ONLY
  7941.  
  7942. OPEN SysComCursor
  7943.  
  7944. FETCH NEXT FROM SysComCursor into @SyscomText
  7945.  
  7946. WHILE @@fetch_status >= 0
  7947. BEGIN
  7948.  
  7949.     SELECT  @BasePos    = 1
  7950.     SELECT  @CurrentPos    = 1
  7951.     SELECT    @TextLength = LEN(@SyscomText)
  7952.  
  7953.     WHILE @CurrentPos  != 0
  7954.     BEGIN
  7955.         --Looking for end of line followed by carriage return
  7956.         SELECT @CurrentPos =   CHARINDEX(char(13)+char(10), @SyscomText, @BasePos)
  7957.  
  7958.         --If carriage return found
  7959.         IF @CurrentPos != 0
  7960.         BEGIN
  7961.             /*If new value for @Lines length will be > then the
  7962.             **set length then insert current contents of @line
  7963.             **and proceed.
  7964.             */
  7965.             While (isnull(LEN(@Line),0) + @BlankSpaceAdded + @CurrentPos-@BasePos + @LFCR) > @DefinedLength
  7966.             BEGIN
  7967.                 SELECT @AddOnLen = @DefinedLength-(isnull(LEN(@Line),0) + @BlankSpaceAdded)
  7968.                 INSERT #CommentText VALUES
  7969.                 ( @LineId, 
  7970.                   isnull(@Line, N'') + isnull(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''))
  7971.                 SELECT @Line = NULL, @LineId = @LineId + 1,
  7972.                        @BasePos = @BasePos + @AddOnLen, @BlankSpaceAdded = 0
  7973.             END
  7974.             SELECT @Line    = isnull(@Line, N'') + isnull(SUBSTRING(@SyscomText, @BasePos, @CurrentPos-@BasePos + @LFCR), N'')
  7975.             SELECT @BasePos = @CurrentPos+2
  7976.             INSERT #CommentText VALUES( @LineId, @Line )
  7977.             SELECT @LineId = @LineId + 1
  7978.             SELECT @Line = NULL
  7979.         END
  7980.         ELSE
  7981.         --else carriage return not found
  7982.         BEGIN
  7983.             IF @BasePos <= @TextLength
  7984.             BEGIN
  7985.                 /*If new value for @Lines length will be > then the
  7986.                 **defined length
  7987.                 */
  7988.                 While (isnull(LEN(@Line),0) + @BlankSpaceAdded + @TextLength-@BasePos+1 ) > @DefinedLength
  7989.                 BEGIN
  7990.                     SELECT @AddOnLen = @DefinedLength - (isnull(LEN(@Line),0)  + @BlankSpaceAdded )
  7991.                     INSERT #CommentText VALUES
  7992.                     ( @LineId, 
  7993.                       isnull(@Line, N'') + isnull(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''))
  7994.                     SELECT @Line = NULL, @LineId = @LineId + 1,
  7995.                         @BasePos = @BasePos + @AddOnLen, @BlankSpaceAdded = 0
  7996.                 END
  7997.                 SELECT @Line = isnull(@Line, N'') + isnull(SUBSTRING(@SyscomText, @BasePos, @TextLength-@BasePos+1 ), N'')
  7998.                 if charindex(' ', @SyscomText, @TextLength+1 ) > 0
  7999.                 BEGIN
  8000.                     SELECT @Line = @Line + ' ', @BlankSpaceAdded = 1
  8001.                 END
  8002.                 BREAK
  8003.             END
  8004.         END
  8005.     END
  8006.  
  8007.     FETCH NEXT FROM SysComCursor into @SyscomText
  8008. END 
  8009.  
  8010. IF @Line is NOT NULL
  8011.     INSERT #CommentText VALUES( @LineId, @Line )
  8012.  
  8013. select Text from #CommentText order by LineId
  8014.  
  8015. CLOSE  SysComCursor
  8016. DEALLOCATE     SysComCursor
  8017.  
  8018. DROP TABLE     #CommentText
  8019.  
  8020. return (0) -- sp_helptext
  8021. go
  8022.  
  8023.  
  8024. --Running this create AFTER create sp_helpgroup.
  8025. raiserror(15339,-1,-1,'sp_helpuser')
  8026. go
  8027. CREATE PROCEDURE sp_helpuser  --- 1996/08/14 10:33
  8028.     @name_in_db       sysname    = NULL --User,Group,Alias
  8029. AS
  8030.  
  8031. Set nocount on
  8032. Set ansi_warnings off
  8033.  
  8034. Declare
  8035.     @RetCode               int
  8036.    ,@_rowcount             int
  8037.  
  8038. Declare
  8039.     @charMaxLen_UsName     varchar(11)
  8040.    ,@charMaxLen_GrName     varchar(11)
  8041.    ,@charMaxLen_LoName     varchar(11)
  8042.    ,@charMaxLen_DbName     varchar(11)
  8043.  
  8044. Declare
  8045.     @Name1Type             char(2)
  8046.    ,@CMaxUsUID             smallint
  8047.  
  8048. -----------------------  create holding table  --------------------
  8049. /*Create temp table before any DML to ensure dynamic*/
  8050.  
  8051. Create Table #tb1_uga
  8052.    (
  8053.     zUserName        sysname        Null
  8054.    ,zGroupName       sysname        Null
  8055.    ,zLoginName       sysname        Null
  8056.    ,zDefDBName       sysname        Null
  8057.    ,zUID             smallint       Null
  8058.    ,zSUID            smallint       Null
  8059.    )
  8060.  
  8061. --------
  8062.  
  8063. Select
  8064.     @RetCode               = 0
  8065.    ,@Name1Type             = Null
  8066.    ,@CMaxUsUID               = 16383
  8067.  
  8068.  
  8069. -------------  What type of value (U,G,A) was input?  --------------
  8070.  
  8071. -------- NULL
  8072.  
  8073. IF (@name_in_db IS Null)
  8074.    begin
  8075.  
  8076.    Select @Name1Type = '-'
  8077.  
  8078.  
  8079.    INSERT into  #tb1_uga
  8080.                (
  8081.                 zUserName
  8082.                ,zGroupName
  8083.                ,zLoginName
  8084.                ,zDefDBName
  8085.                ,zUID
  8086.                ,zSUID
  8087.                )
  8088.       SELECT
  8089.                    usu.name
  8090.                   ,case 
  8091.                     when (usg.uid is null) then 'public'
  8092.                     else usg.name
  8093.                    end
  8094.                   ,lo.loginname
  8095.                   ,lo.dbname
  8096.                   ,usu.uid
  8097.                   ,suser_id(suser_sname(usu.sid))
  8098.          from
  8099.                    sysusers    usu left outer join
  8100.                     (sysmembers mem inner join sysusers usg on mem.groupuid = usg.uid) on usu.uid = mem.memberuid
  8101.                    left outer join master.dbo.syslogins  lo on usu.sid = lo.sid
  8102.          where
  8103.                    (usu.islogin = 1 and usu.isaliased = 0 and usu.hasdbaccess = 1) and
  8104.                    (usg.issqlrole = 1 or usg.uid is null)
  8105.  
  8106.  
  8107.    GOTO LABEL_25NAME1TYPEKNOWN
  8108.  
  8109.    end
  8110.  
  8111.  
  8112. -------- USER
  8113.  
  8114. INSERT   into   #tb1_uga
  8115.                (
  8116.                 zUserName
  8117.                ,zGroupName
  8118.                ,zLoginName
  8119.                ,zDefDBName
  8120.                ,zUID
  8121.                ,zSUID
  8122.                )
  8123.       SELECT
  8124.                    usu.name
  8125.                   ,case 
  8126.                     when (usg.uid is null) then 'public'
  8127.                     else usg.name
  8128.                    end
  8129.                   ,lo.loginname
  8130.                   ,lo.dbname
  8131.                   ,usu.uid
  8132.                   ,suser_id(suser_sname(usu.sid))
  8133.          from
  8134.                    sysusers    usu left outer join
  8135.                     (sysmembers mem inner join sysusers usg on mem.groupuid = usg.uid) on usu.uid = mem.memberuid
  8136.                    left outer join master.dbo.syslogins  lo on usu.sid = lo.sid
  8137.          where
  8138.                    (usu.islogin = 1 and usu.isaliased = 0 and usu.hasdbaccess = 1) and
  8139.                    (usg.issqlrole = 1 or usg.uid is null) and
  8140.                    usu.name    = @name_in_db
  8141.  
  8142.  
  8143. Select @_rowcount = @@rowcount
  8144.  
  8145.  
  8146. IF (@_rowcount > 0)
  8147.    begin
  8148.    Select @Name1Type = 'US'
  8149.  
  8150.    GOTO LABEL_25NAME1TYPEKNOWN
  8151.  
  8152.    end
  8153.  
  8154.  
  8155.  -------- ALIAS
  8156.  
  8157. INSERT   into   #tb1_uga
  8158.                (
  8159.                 zUserName
  8160.                ,zGroupName
  8161.                ,zLoginName
  8162.                ,zDefDBName
  8163.                ,zUID
  8164.                ,zSUID
  8165.                )
  8166.    
  8167.     SELECT
  8168.                    usu.name
  8169.                   ,case 
  8170.                     when (usg.uid is null) then 'public'
  8171.                     else usg.name
  8172.                    end
  8173.                   ,lo.loginname
  8174.                   ,lo.dbname
  8175.                   ,usu.uid
  8176.                   ,suser_id(suser_sname(usu.sid))
  8177.          from       sysalternates al inner join 
  8178.                    (sysusers    usu left outer join
  8179.                     (sysmembers mem inner join sysusers usg on mem.groupuid = usg.uid) on usu.uid = mem.memberuid
  8180.                    left outer join master.dbo.syslogins  lo on usu.sid = lo.sid) on al.altsuid  = usu.suid
  8181.          where
  8182.                    (usu.islogin = 1 and usu.isaliased = 0) and
  8183.                    (usg.issqlrole = 1 or usg.uid is null) and
  8184.                    al.suid     = suser_id(@name_in_db)
  8185.  
  8186.  
  8187. Select @_rowcount = @@rowcount
  8188.  
  8189.  
  8190. IF (@_rowcount > 0)
  8191.    begin
  8192.    Select @Name1Type = 'AL'
  8193.  
  8194.    GOTO LABEL_25NAME1TYPEKNOWN
  8195.  
  8196.    end
  8197.  
  8198.  
  8199. -------- GROUP
  8200. IF EXISTS
  8201.       (SELECT * FROM sysusers
  8202.          WHERE  name = @name_in_db
  8203.          AND (issqlrole = 1)
  8204.       )
  8205.    begin
  8206.    Select @Name1Type = 'GR'
  8207.  
  8208.    Execute sp_helpgroup @name_in_db
  8209.  
  8210.    GOTO LABEL_75FINAL  --Done
  8211.  
  8212.    end
  8213.  
  8214. -------- Error
  8215. Raiserror(15198,-1,-1 ,@name_in_db)  --Input Name is unfound
  8216. Select @RetCode = @RetCode | 1
  8217.  
  8218. GOTO LABEL_75FINAL
  8219.  
  8220. --------
  8221.  
  8222.  
  8223. LABEL_25NAME1TYPEKNOWN:
  8224.  
  8225.  
  8226. -----------------------  Printout the report  -------------------------
  8227.  
  8228. -------- Preparations for dynamic exec
  8229.  
  8230. SELECT
  8231.           @charMaxLen_UsName  = convert( varchar,
  8232.                   isnull( max( datalength( zUserName)),8))
  8233.  
  8234.          ,@charMaxLen_GrName  = convert( varchar,
  8235.                   isnull( max( datalength( zGroupName)),9))
  8236.  
  8237.          ,@charMaxLen_LoName  = convert( varchar,
  8238.                   isnull( max( datalength( zLoginName)),9))
  8239.  
  8240.          ,@charMaxLen_DbName  = convert( varchar,
  8241.                   isnull( max( datalength( zDefDBName)),9))
  8242.    from
  8243.           #tb1_uga
  8244.  
  8245.  
  8246. -------- Dynamic EXEC() to printout report
  8247.  
  8248.  
  8249. EXECUTE(
  8250. '
  8251. SELECT
  8252.              ''UserName''  =
  8253.                      substring(zUserName ,1,' + @charMaxLen_UsName + ')
  8254.  
  8255.             ,''GroupName'' =
  8256.                      substring(zGroupName,1,' + @charMaxLen_GrName + ')
  8257.  
  8258.             ,''LoginName'' =
  8259.                      substring(zLoginName,1,' + @charMaxLen_LoName + ')
  8260.  
  8261.             ,''DefDBName'' =
  8262.                      substring(zDefDBName,1,' + @charMaxLen_DbName + ')
  8263.  
  8264.             ,''UserID''    = convert(char(6),zUID)
  8265.  
  8266.             ,''SUserID''   = convert(char(7),zSUID)
  8267.       from
  8268.              #tb1_uga
  8269.       order by
  8270.              1
  8271. '
  8272. )
  8273.  
  8274. -----------------------  A little extra nice-to-have
  8275.  
  8276. IF (@Name1Type IN ('-','US'))
  8277.    begin
  8278.  
  8279.    IF EXISTS (SELECT * FROM #tb1_uga tb1 ,sysalternates al, sysusers us
  8280.                        WHERE tb1.zUID = us.uid and us.suid = al.altsuid 
  8281.              )
  8282.       begin
  8283.  
  8284.       SELECT   'LoginName' = suser_name(al.suid)
  8285.               ,'UserNameAliasedTo' = tb1.zUserName
  8286.          from  #tb1_uga tb1 ,sysalternates al, sysusers us
  8287.          WHERE tb1.zUID = us.uid and us.suid = al.altsuid
  8288.          order by 1
  8289.  
  8290.       end
  8291.    end
  8292.  
  8293.  
  8294. -----------------------  Finalization  ----------------------
  8295.  
  8296.  
  8297. LABEL_75FINAL:
  8298.  
  8299.  
  8300. IF (object_id('tempdb..#tb1_uga') IS not Null)
  8301.             Drop Table #tb1_uga
  8302.  
  8303. return (0) -- sp_helpuser
  8304. go
  8305.  
  8306.  
  8307. raiserror(15339,-1,-1,'sp_indexoption')
  8308. go
  8309. /*ANSI_NULLS on for creation of sp_indexoption*/
  8310. Set ansi_nulls on
  8311. go
  8312. create procedure sp_indexoption  --- 1996/09/09 14:17
  8313.     @IndexNamePattern      ncharacter varying(1035)
  8314.  
  8315.    ,@OptionName            character varying(35)   = null
  8316.    ,@OptionValue           character varying(12)   = null
  8317. as
  8318.  
  8319. Set nocount       on
  8320. Set ansi_warnings on
  8321.  
  8322. Declare @exec_stmt nvarchar(975)
  8323.  
  8324. Declare
  8325.        @RetCode            integer
  8326.       ,@int1               integer
  8327. Declare
  8328.        @CurrentDBName      sysname
  8329.       ,@CountMatchedInd    integer
  8330.       ,@CountUpdRows2      integer
  8331.       ,@RowLocksStr        varchar(35)
  8332.       ,@PageLocksStr       varchar(35)
  8333.       ,@Status_csr_11      integer
  8334.       ,@TabId              integer
  8335.       ,@IndId              integer
  8336.       ,@LockStatus         integer
  8337.       ,@BitLogic           varchar(9)
  8338. Declare
  8339.        @WOptionName        character varying(35)  -- spt_values.name
  8340.       ,@WOptionNum         integer
  8341.       ,@charWOptionNum     varchar(12)
  8342.       ,@WOptionValue       character varying( 6)  -- T/F
  8343.       ,@intOptionValue     integer
  8344. Declare
  8345.        @UnqualName         sysname    -- ind or tab
  8346.       ,@QualName1          sysname    -- tab or own
  8347.       ,@QualName2          sysname    -- own or db
  8348.       ,@QualName3          sysname    -- db or naught
  8349.  
  8350.       ,@WIndexName         sysname
  8351.       ,@WTableName         sysname
  8352.       ,@WOwnerName         sysname
  8353.       ,@WDatabaseName      sysname
  8354.       ,@QuotedName         ncharacter varying (264)
  8355.  
  8356. /*Create temp tables before any DML to ensure dynamic*/
  8357. CREATE table #t1
  8358.    (
  8359.     ObjId          integer     not null
  8360.    ,IndId        integer     not null
  8361.    ,CurrentValues  integer     not null
  8362.    )
  8363. CREATE unique
  8364.    index    ix2
  8365.    on       #t1   (ObjId, IndId)
  8366.  
  8367. -----------------------------
  8368.  
  8369. Select
  8370.        @RetCode            = 0   --  =0 is good,  >0 is bad.
  8371.       ,@CurrentDBName      = db_name()
  8372.       ,@CountMatchedInd    = 0
  8373.       ,@CountUpdRows2      = 0
  8374.       ,@RowLocksStr        = 'allowrowlocks'
  8375.       ,@PageLocksStr       = 'allowpagelocks'
  8376.       ,@Status_csr_11      = 0  -- 0x01 bit =Declared; 0x02 bit =Open.
  8377.       ,@TabId              = null
  8378.       ,@IndId              = null
  8379. Select
  8380.        @UnqualName         = null
  8381.       ,@QualName1          = null
  8382.       ,@QualName2          = null
  8383.       ,@QualName3          = null
  8384.       ,@WIndexName         = null
  8385.       ,@WTableName         = null  -- tab
  8386.       ,@WOwnerName         = null  -- own
  8387.       ,@WDatabaseName      = null  -- db
  8388.  
  8389.  
  8390. --------------------- Basic parm edits  -------------------
  8391.  
  8392. IF (@IndexNamePattern IS null)
  8393.    begin
  8394.    raiserror(15223, -1,-1,'@IndexNamePattern')
  8395.    Select @RetCode = @@error
  8396.    GOTO LABEL_86_RETURN
  8397.    end
  8398.  
  8399. IF (@OptionName is null)
  8400.    begin
  8401.    ------- Report, then bye.
  8402.  
  8403.    SELECT
  8404.                    val.name   as 'Available Index Options'
  8405.                   ,val.status as 'Default Value'
  8406.          from      master.dbo.spt_values  val
  8407.          where     val.type   = 'IDX'
  8408.          and       val.number > 0
  8409.          order by  val.name
  8410.  
  8411.    GOTO LABEL_86_RETURN
  8412.  
  8413.    end
  8414.  
  8415.  
  8416. --------  Gather spt_values info (only index opts with 'IDX' rows are docu).
  8417.  
  8418.  
  8419. SELECT
  8420.              @WOptionName        = min(val.name)
  8421.             ,@WOptionNum         = min(val.number)
  8422.             ,@int1               = count(*)
  8423.       from   master.dbo.spt_values  val
  8424.       where  val.type            = 'IDX'
  8425.       and    val.number          > 0
  8426.       and    lower(val.name) like (lower(@OptionName) + '%')
  8427.  
  8428. IF (@int1 <> 1)
  8429.    begin
  8430.    raiserror(15386,-1,-1,@OptionName,@int1)
  8431.    Select @RetCode = @@error
  8432.    GOTO LABEL_86_RETURN
  8433.    end
  8434.  
  8435. Select @charWOptionNum = convert(varchar,@WOptionNum)
  8436.  
  8437.  
  8438. -------- Parse apart the perhaps dots-qualified name.  ---------------
  8439. -- This can 
  8440. -- be database.owner.table.index 
  8441. -- or database.owner.table
  8442. -- or owner.table.index
  8443. -- or owner.table
  8444. -- or table.index
  8445. -- or table
  8446. -- but never just index
  8447.  
  8448. -- get name parts --
  8449. select @UnqualName = parsename(@IndexNamePattern, 1),
  8450.         @QualName1 = parsename(@IndexNamePattern, 2),
  8451.         @QualName2 = parsename(@IndexNamePattern, 3),
  8452.         @QualName3 = parsename(@IndexNamePattern, 4)
  8453. IF (@UnqualName is NULL)
  8454.    begin
  8455.    raiserror(15253,-1,-1,@IndexNamePattern)
  8456.    Select @RetCode = @@error
  8457.    GOTO LABEL_86_RETURN
  8458.    end
  8459.  
  8460.  
  8461. ------------------  Verify database.
  8462.  
  8463.  
  8464. Select @WDatabaseName = @QualName3
  8465. Select @WOwnerName = @QualName2
  8466.  
  8467. IF (@WDatabaseName is null)
  8468. begin
  8469.    if (@WOwnerName IS NOT NULL)
  8470.    begin
  8471.      if (user_id (@WOwnerName) IS NULL)
  8472.      begin
  8473.         Select @WDatabaseName = @CurrentDBName
  8474.         SELECT @WOwnerName = NULL  -- shift
  8475.      end
  8476.    end
  8477.    else
  8478.    begin
  8479.      Select @WDatabaseName = @CurrentDBName
  8480.    end
  8481. end
  8482.  
  8483. -- @WDatabaseName should have DBName at this point
  8484. IF (@WDatabaseName <> @CurrentDBName)
  8485.    begin
  8486.    raiserror(15387,-1,-1)
  8487.    Select @RetCode = @@error
  8488.    GOTO LABEL_86_RETURN
  8489.    end
  8490.  
  8491.  
  8492. ------------------  Settle owner.
  8493. select @WTableName = @QualName1
  8494. if (@WOwnerName is null)
  8495. begin
  8496.   if (user_id(@WTableName) is not null)
  8497.   begin
  8498.     Select @WOwnerName = @WTableName -- shift
  8499.     select @WTableName = null
  8500.   end
  8501. end
  8502.  
  8503. IF (@WOwnerName is null)  -- Owner not part of any qualification.
  8504.    begin
  8505.    Select @WOwnerName = user_name()  
  8506.    end
  8507.  
  8508. ------------------ Settle table and index names
  8509. if (@WTableName is null)
  8510. begin
  8511.   select @WTableName = @UnqualName
  8512.   select @WIndexName = null
  8513. end
  8514. else
  8515. begin
  8516.   select @WIndexName = @UnqualName
  8517. end
  8518.  
  8519. ------------------  Are zero objects matched?
  8520.  
  8521. SELECT          @CountMatchedInd = count(*)
  8522.       from      sysobjects       sysobj
  8523.                 ,sysindexes      sysind
  8524.       where     sysobj.xtype      = 'U '
  8525.       and       user_name(sysobj.uid) = @WOwnerName -- now owner
  8526.       and       sysobj.name           = @WTableName -- now table
  8527.       and       sysind.indid <> 255 -- no text
  8528.       and       ( @WIndexName is null or sysind.name = @WIndexName)
  8529.       and       sysind.id = sysobj.id  -- join
  8530.  
  8531. IF (@CountMatchedInd = 0)
  8532.    begin
  8533.    raiserror(15388,-1,-1,@IndexNamePattern)
  8534.    Select @RetCode = @@error
  8535.    GOTO LABEL_86_RETURN
  8536.    end
  8537.  
  8538.  
  8539. -------------  Project any option info into one common format/location.  -----
  8540. IF (@WOptionName in (@RowLocksStr, @PageLocksStr))
  8541.    begin
  8542.    INSERT into #t1
  8543.          (ObjId , IndId, CurrentValues)
  8544.       SELECT
  8545.                 sysind.id  ,sysind.indid, sysind.lockflags
  8546.          from
  8547.                 sysobjects       sysobj
  8548.                 , sysindexes     sysind
  8549.       where     sysobj.xtype      = 'U '
  8550.       and       user_name(sysobj.uid) = @WOwnerName -- now owner
  8551.       and       sysobj.name           = @WTableName -- now table
  8552.       and       sysind.indid <> 255 -- no text
  8553.       and       (@WIndexName is null or sysind.name = @WIndexName)
  8554.       and       sysind.id = sysobj.id  -- join
  8555.    end
  8556.  
  8557.  
  8558. -----------------  Was option value parm specified?  ---------------
  8559.  
  8560.  
  8561. Select @WOptionValue = lower(@OptionValue)
  8562.  
  8563.  
  8564. IF (@OptionValue is null)
  8565.    begin
  8566.    --    Report current option settings, then bye.
  8567.  
  8568.    SELECT
  8569.                 CASE
  8570.                   When t1.CurrentValues & @WOptionNum <> 0 Then 'False'  -- reverse logic settings
  8571.                   When t1.CurrentValues & @WOptionNum  = 0 Then 'True '
  8572.                 END
  8573.                 as 'Option Status'
  8574.                ,@WTableName        as 'Table Name'
  8575.                ,sysind.name        as 'Index Name'
  8576.                ,@WOwnerName        as 'Owner Name'
  8577.          from
  8578.                 sysindexes   sysind
  8579.                ,#t1           t1
  8580.          where  sysind.id     = t1.ObjId
  8581.          and    sysind.indid  = t1.IndId
  8582.          order by
  8583.                 1 ,2 ,3
  8584.  
  8585.  
  8586.    GOTO LABEL_86_RETURN
  8587.  
  8588.    end
  8589.  
  8590.  
  8591. IF (@WOptionValue in ('1' ,'on' ,'yes'))
  8592.    begin
  8593.    Select @WOptionValue  = 'true'
  8594.    end
  8595.  
  8596. IF (@WOptionValue in ('0' ,'off' ,'no'))
  8597.    begin
  8598.    Select @WOptionValue  = 'false'
  8599.    end
  8600.  
  8601.  
  8602. IF (@WOptionValue not in ('true','false'))
  8603.    begin
  8604.    raiserror(15389,-1,-1,@OptionValue)
  8605.    Select @RetCode = @@error
  8606.    GOTO LABEL_86_RETURN
  8607.    end
  8608.  
  8609. Select @intOptionValue =
  8610.             CASE @WOptionValue
  8611.                When 'true'  Then 1
  8612.                When 'false' Then 0
  8613.             END
  8614.  
  8615. --------------------------  Security  ------------------
  8616.  
  8617.  
  8618. --SA & DBO generally have no security restrictions.
  8619. IF not (is_member('db_owner') = 1) and
  8620.     not (is_member('db_ddladmin') = 1)
  8621.    begin
  8622.  
  8623.    IF (is_member(@WOwnerName) <> 1)
  8624.       begin
  8625.       raiserror(15390,-1,-1,@WOptionName)
  8626.       Select @RetCode = @@error
  8627.       GOTO LABEL_86_RETURN
  8628.       end
  8629.    end
  8630.  
  8631.  
  8632. ------------------  Prepare cursor  -------------------------
  8633.  
  8634. -- beware of inverse logic here; bit on means inhibit that type of
  8635. -- locking
  8636. IF (@intOptionValue = 0)    --Want it False,
  8637.    begin
  8638.    Select @BitLogic = '  = '   --but is False currently.
  8639.    end
  8640. ELSE                        --Want it True,
  8641.    begin
  8642.    Select @BitLogic = ' <> '   --but is True  currently.
  8643.    end
  8644.  
  8645. select @exec_stmt = '
  8646. DECLARE         csr_11_tabid
  8647.                 insensitive
  8648.             cursor for
  8649.    SELECT
  8650.                 ObjId, IndId, CurrentValues
  8651.          from    #t1           t1
  8652.          where  
  8653.                 t1.CurrentValues & ' + @charWOptionNum + ' ' + @BitLogic + ' 0'
  8654. EXECUTE(@exec_stmt)
  8655. Select @Status_csr_11 = 1
  8656.  
  8657. Open csr_11_tabid
  8658. Select @Status_csr_11 = @Status_csr_11 | 2
  8659.  
  8660. WHILE (11=11)
  8661. begin
  8662.  
  8663.    FETCH    next from csr_11_tabid
  8664.          into
  8665.                 @TabId, @IndId, @LockStatus
  8666.  
  8667.    IF (@@fetch_status <> 0)
  8668.       begin
  8669.       Deallocate csr_11_tabid
  8670.       Select @Status_csr_11 = 0
  8671.       BREAK
  8672.       end
  8673.  
  8674.    Select @CountUpdRows2 = @CountUpdRows2 + 1
  8675.  
  8676.    -- build a guoted ownername.tablename
  8677.    select @QuotedName = QuoteName(@WOwnerName,'[') + '.' + QuoteName (@WTableName,'[') 
  8678.  
  8679.  
  8680.    -- reverse logic here; bit on means inhibit this type of locking
  8681.    IF (@intOptionValue = 0)    --Want it False,
  8682.    begin
  8683.      select @LockStatus = @LockStatus | @WOptionNum
  8684.    end
  8685.    ELSE                        --Want it True,
  8686.    begin
  8687.      select @LockStatus = @LockStatus & (~@WOptionNum) 
  8688.    end
  8689.    -- update the sysindexes row
  8690.    --
  8691.    begin tran
  8692.     dbcc LockObjectSchema (@QuotedName)
  8693.     update sysindexes set lockflags = @LockStatus
  8694.     where indid = @IndId and id = @TabId
  8695.    commit tran
  8696.  
  8697. end --loop 11
  8698.  
  8699.  
  8700. -----------------  Finalization  -------------------------
  8701.  
  8702.  
  8703. LABEL_75_FINAL:
  8704.  
  8705. Raiserror(15391,-1,-1,@CountMatchedInd,@WOptionName,@OptionValue,@CountUpdRows2)
  8706.  
  8707. LABEL_86_RETURN:
  8708.  
  8709. IF (@Status_csr_11 > 0)
  8710.    begin
  8711.    Deallocate csr_11
  8712.    end
  8713.  
  8714. IF (object_id('tempdb..#t1') is not null)
  8715.    begin
  8716.             drop table #t1
  8717.    end
  8718.  
  8719. Return @RetCode  --sp_indexoption
  8720. go
  8721. Set ansi_nulls off
  8722. go
  8723. /*ANSI_NULLS off for after creation of sp_indexoption*/
  8724. go
  8725.  
  8726.  
  8727. raiserror(15339,-1,-1,'sp_lock')
  8728. go
  8729. create procedure sp_lock --- 1996/04/08 00:00
  8730. @spid1 int = NULL,        /* server process id to check for locks */
  8731. @spid2 int = NULL        /* other process id to check for locks */
  8732. as
  8733.  
  8734. set nocount on
  8735. /*
  8736. **  Show the locks for both parameters.
  8737. */
  8738. if @spid1 is not NULL
  8739. begin
  8740.     select     convert (smallint, req_spid) As spid, 
  8741.         rsc_dbid As dbid, 
  8742.         rsc_objid As ObjId,
  8743.         rsc_indid As IndId,
  8744.         substring (v.name, 1, 4) As Type,
  8745.         substring (rsc_text, 1, 16) as Resource,
  8746.         substring (u.name, 1, 8) As Mode,
  8747.         substring (x.name, 1, 5) As Status
  8748.  
  8749.     from     master.dbo.syslockinfo,
  8750.         master.dbo.spt_values v,
  8751.         master.dbo.spt_values x,
  8752.         master.dbo.spt_values u
  8753.  
  8754.     where   master.dbo.syslockinfo.rsc_type = v.number
  8755.             and v.type = 'LR'
  8756.             and master.dbo.syslockinfo.req_status = x.number
  8757.             and x.type = 'LS'
  8758.             and master.dbo.syslockinfo.req_mode + 1 = u.number
  8759.             and u.type = 'L'
  8760.             
  8761.             and req_spid in (@spid1, @spid2)
  8762. end
  8763.  
  8764. /*
  8765. **  No parameters, so show all the locks.
  8766. */
  8767. else
  8768. begin
  8769.     select     convert (smallint, req_spid) As spid, 
  8770.         rsc_dbid As dbid, 
  8771.         rsc_objid As ObjId,
  8772.         rsc_indid As IndId,
  8773.         substring (v.name, 1, 4) As Type,
  8774.         substring (rsc_text, 1, 16) as Resource,
  8775.         substring (u.name, 1, 8) As Mode,
  8776.         substring (x.name, 1, 5) As Status
  8777.  
  8778.     from     master.dbo.syslockinfo,
  8779.         master.dbo.spt_values v,
  8780.         master.dbo.spt_values x,
  8781.         master.dbo.spt_values u
  8782.  
  8783.     where   master.dbo.syslockinfo.rsc_type = v.number
  8784.             and v.type = 'LR'
  8785.             and master.dbo.syslockinfo.req_status = x.number
  8786.             and x.type = 'LS'
  8787.             and master.dbo.syslockinfo.req_mode + 1 = u.number
  8788.             and u.type = 'L'
  8789.     order by spid 
  8790. end
  8791.  
  8792. return (0) -- sp_lock
  8793. go
  8794.  
  8795. checkpoint
  8796. go
  8797.  
  8798. raiserror(15339,-1,-1,'sp_logdevice')
  8799. go
  8800. create procedure sp_logdevice
  8801. @dbname sysname,
  8802. @devicename sysname
  8803. as
  8804. declare @stmt nvarchar(1150)
  8805. declare @countrows int
  8806. declare @size nvarchar (10)
  8807. declare @maxsize nvarchar (10)
  8808. declare @growth nvarchar (10)
  8809. declare @filename sysname
  8810. set nocount on
  8811.  
  8812. -- Make sure the database exists
  8813. --
  8814. if not exists (select * from master.dbo.sysdatabases where name = @dbname)
  8815.     begin
  8816.         raiserror(15010,-1,-1,@dbname)
  8817.         return (1)
  8818.     end
  8819.  
  8820. -- Make sure the file exists and it should be in sysdevices as this is only
  8821. -- for older syntax. 
  8822. --
  8823. if not exists (select * from master.dbo.sysdevices where name = @devicename)
  8824.     begin
  8825.         raiserror(15012,-1,-1,@devicename)
  8826.         return (1)
  8827.     end
  8828.  
  8829. -- Calculate the specs of the current file and save it into a temp table
  8830. --
  8831. create table #tempsize (size int, growth int, maxsize int, filename sysname) 
  8832. select @stmt = 'INSERT #tempsize SELECT size, growth, maxsize, filename FROM ' 
  8833.                 + @dbname + '.dbo.sysfiles WHERE name = '''
  8834.                 + @devicename + ''''
  8835. exec (@stmt)
  8836. select @countrows = count (*) from #tempsize
  8837.  
  8838. -- disconnect with devices and database
  8839. --
  8840. if @countrows <> 1
  8841.     begin
  8842.         raiserror(15012,-1,-1,@devicename)
  8843.         return (1)
  8844.     end
  8845.  
  8846. select @stmt = 'ALTER DATABASE ' + @dbname + ' REMOVE FILE ' + @devicename
  8847. exec (@stmt)
  8848. if @@error <> 0
  8849.     begin
  8850.         raiserror(15319,-1,-1,@dbname,@devicename)
  8851.         return(1)
  8852.     end
  8853. select @size = convert(nvarchar(10), size/128),
  8854.   @maxsize = convert(nvarchar(10), maxsize),
  8855.   @growth = convert(nvarchar(10), growth * 8),
  8856.   @filename = filename
  8857. from #tempsize
  8858.  
  8859. if (@maxsize = '-1')
  8860. begin
  8861.     select @maxsize = 'UNLIMITED'
  8862. end
  8863. else
  8864. begin
  8865.     select @maxsize = (convert (int, @maxsize)) / 128
  8866. end
  8867.  
  8868. select @stmt = 'ALTER DATABASE ' + @dbname 
  8869.             + ' ADD LOG FILE (NAME = [' 
  8870.             + @devicename + '], FILENAME = [' 
  8871.             + @filename + '], SIZE = '
  8872.             + @size + ', MAXSIZE = ' 
  8873.             + @maxsize + ', FILEGROWTH = '
  8874.             + @growth + 'KB)'
  8875. exec (@stmt)
  8876. if @@error=0
  8877.       begin
  8878.       raiserror(15318,-1,-1,@dbname,@devicename)
  8879.       end
  8880. else
  8881.       begin
  8882.       raiserror(15319,-1,-1,@dbname,@devicename)
  8883.       return (1)
  8884.       end
  8885.  
  8886. return (0) -- sp_logdevice
  8887. GO
  8888.  
  8889.  
  8890. raiserror(15339,-1,-1,'sp_helpremotelogin')
  8891. go
  8892. create procedure sp_helpremotelogin --- 1996/04/08 00:00
  8893. @remoteserver sysname = NULL,    /* remote server name */
  8894. @remotename sysname = NULL        /* remote login name */
  8895. as
  8896. set nocount on
  8897.  
  8898. /*
  8899. **  If no server given, get 'em all.
  8900. */
  8901. if not exists (select * from master.dbo.sysservers s, master.dbo.sysremotelogins r
  8902.     where s.srvid = r.remoteserverid
  8903.         and (@remoteserver is null or s.srvname = @remoteserver ))
  8904.     begin
  8905.         if @remoteserver is null
  8906.             begin
  8907.                 raiserror(15200,-1,-1)
  8908.                 return (0)
  8909.             end
  8910.  
  8911.         raiserror(15201,-1,-1,@remoteserver)
  8912.         return (1)
  8913.     end
  8914.  
  8915. /*
  8916. **  If no remotename given, get 'em all.
  8917. */
  8918. if not exists (select * from master.dbo.sysremotelogins
  8919.     where (@remotename is null or isnull(remoteusername, ' ') = @remotename))
  8920.     begin
  8921.         if @remotename is null
  8922.             begin
  8923.                 raiserror(15202,-1,-1)
  8924.                 return (1)
  8925.             end
  8926.  
  8927.         raiserror(15203,-1,-1,@remotename)
  8928.         return (1)
  8929.  
  8930.     end
  8931.  
  8932. /*
  8933. **  Check for empty results.
  8934. */
  8935. if not exists (select *
  8936.     from master.dbo.sysremotelogins r, master.dbo.sysservers s
  8937.     where ( @remotename is null or isnull(r.remoteusername, ' ') = @remotename)
  8938.         and s.srvid = r.remoteserverid
  8939.         and (@remoteserver is null or s.srvname = @remoteserver))
  8940.     begin
  8941.         raiserror(15204,-1,-1,@remotename,@remoteserver)
  8942.         return (1)
  8943.     end
  8944.  
  8945. /*
  8946. **  Select the information.
  8947. */
  8948. select server = substring(s.srvname, 1, 22),
  8949.     local_user_name =
  8950.         substring(isnull(suser_sname(r.sid), '** use local name **'), 1, 22),
  8951.     remote_user_name =
  8952.         substring(isnull(r.remoteusername, '** mapped locally **'), 1, 22),
  8953.     options = case datalength(v.name) 
  8954.                 when null then '' 
  8955.                 when 0 then '' 
  8956.                 else substring(v.name, 1, 9) 
  8957.               end
  8958.         from master.dbo.sysservers s, master.dbo.sysremotelogins r,
  8959.             master.dbo.spt_values v
  8960.     where s.srvid = r.remoteserverid
  8961.         and (@remoteserver is null or s.srvname = @remoteserver)
  8962.         and (@remotename is null or isnull(r.remoteusername, ' ') = @remotename)
  8963.         and v.type = 'F'
  8964.         and v.number = r.status
  8965. order by server, remote_user_name
  8966.  
  8967. return (0) -- sp_helpremotelogin
  8968. go
  8969.  
  8970.  
  8971.  
  8972. raiserror(15339,-1,-1,'sp_helpsort')
  8973. go
  8974. create procedure sp_helpsort --- 1996/04/08 00:00
  8975. AS
  8976. set nocount on
  8977.  
  8978. /*
  8979. ** Now display the Unicode data sorting information
  8980. */
  8981. declare @compflags int
  8982. declare @option varchar(255)
  8983. select @compflags = value from master.dbo.syscurconfigs where config = 1125
  8984. select @option = ''
  8985.  
  8986. if (@compflags & 0x1) = 0x1
  8987. select @option = @option + ' case insensitive'
  8988. else
  8989. select @option = @option + ' case sensitive'
  8990.  
  8991. if (@compflags & 0x2) = 0x2
  8992. select @option = @option + ', accent insensitive'
  8993.  
  8994. if (@compflags & 0x10000) = 0x10000
  8995. select @option = @option + ', kana type insensitive'
  8996.  
  8997. if (@compflags & 0x20000) = 0x20000
  8998. select @option = @option + ', width insensitive'
  8999.  
  9000. select 'Unicode data sorting' = 'Locale ID = ' + convert(char(10), value) 
  9001.     from master.dbo.syscurconfigs where config = 1124
  9002. print @option
  9003. print ''
  9004. print ''
  9005.  
  9006. declare @sortid tinyint, @charid tinyint, @status tinyint
  9007. declare @image binary(1)
  9008. declare @count int, @end_flag int
  9009.  
  9010. declare @string nvarchar(132)
  9011.  
  9012. /*create temp tables before any DML to ensure dynamic*/
  9013. create table #helpsort3 (string nvarchar(132)    NOT NULL)
  9014. create table #helpsort1 (char_val char(1) NOT NULL)
  9015.  
  9016. /*
  9017. ** Get the sortorder ID, character set ID, and status
  9018. */
  9019. select @sortid = id, @charid = csid, @image = convert(binary(1), binarydefinition)
  9020.     from master.dbo.syscharsets, master.dbo.syscurconfigs
  9021.     where id = value and config = 1123
  9022.  
  9023. /*
  9024. ** Get the name and description of the character set and sort order
  9025. */
  9026. if (@sortid is null)
  9027.  BEGIN
  9028.     select @sortid = 0, @charid = 0, @status = 0
  9029.     insert #helpsort3 values ('Character Set = 0, ascii_8')
  9030.     insert #helpsort3 values ('    8-bit ASCII Character Set - System Default')
  9031.     insert #helpsort3 values ('Sort Order = 0, bin_ascii_8')
  9032.     insert #helpsort3 values ('    Binary Ordering - System Default')
  9033.  END
  9034. else
  9035.  BEGIN
  9036.     select @status = convert(tinyint, @image)
  9037.  
  9038.     select @string = 'Character Set = ' + convert(varchar(4), id) + ', ' + name
  9039.         from master.dbo.syscharsets
  9040.         where id = @charid and type = 1001
  9041.  
  9042.     insert into #helpsort3 values (@string)
  9043.  
  9044.     select @count = 1
  9045.     select @end_flag = 1
  9046.  
  9047.     while (@end_flag <> 0)
  9048.     begin
  9049.         select @string = substring(description, @count, 62)
  9050.             from master.dbo.syscharsets
  9051.             where id = @charid and type = 1001
  9052.         select @end_flag = isnull(ascii(@string), 0)
  9053.  
  9054.         if (@end_flag <> 0)
  9055.         begin
  9056.             select @string = '    ' + isnull(@string,'')
  9057.             insert #helpsort3 values (@string)
  9058.         end
  9059.         select @count = @count + 62
  9060.     end
  9061.  
  9062.     select @string = 'Sort Order = ' + convert(varchar(4), id) + ', ' + name
  9063.         from master.dbo.syscharsets
  9064.         where id = @sortid and type = 2001
  9065.  
  9066.     insert into #helpsort3 values (@string)
  9067.  
  9068.     select @count = 1
  9069.     select @end_flag = 1
  9070.  
  9071.     while (@end_flag <> 0)
  9072.     begin
  9073.         select @string = substring(description, @count, 62)
  9074.             from master.dbo.syscharsets
  9075.             where id = @sortid and type = 2001
  9076.         select @end_flag = isnull(ascii(@string), 0)
  9077.  
  9078.         if (@end_flag <> 0)
  9079.         begin
  9080.             select @string = '    ' + isnull(@string,'')
  9081.             insert #helpsort3 values (@string)
  9082.         end
  9083.  
  9084.         select @count = @count + 62
  9085.     end
  9086. END
  9087.  
  9088. select 'Sort Order Description' = string from #helpsort3
  9089.  
  9090. /*
  9091. ** Build the sorted list of characters for this sort order.
  9092. ** If it's not stored in spt_values yet, then put the results in there.
  9093. */
  9094.  
  9095. if not exists (select * from master.dbo.spt_values
  9096.         where type = 'Z'
  9097.             and high = @sortid)
  9098. BEGIN
  9099.     if @charid = 0       /*    ascii_8 has valid values from 32 to 126 */
  9100.     begin
  9101.             select @count = 32
  9102.             while @count <= 126
  9103.             begin
  9104.                 insert #helpsort1 (char_val)
  9105.                     values (char(@count))
  9106.                 select @count = @count + 1
  9107.             end
  9108.     end
  9109.  
  9110.     if @charid = 1      /*     iso_1 has values from 32 to 126, 160 to 255 */
  9111.     begin
  9112.             select @count = 32
  9113.             while @count <= 126
  9114.             begin
  9115.                 insert #helpsort1 (char_val)
  9116.                     values (char(@count))
  9117.                 select @count = @count + 1
  9118.             end
  9119.  
  9120.             select @count = 160
  9121.             while @count <= 255
  9122.             begin
  9123.                    insert #helpsort1 (char_val)
  9124.                         values (char(@count))
  9125.                     select @count = @count + 1
  9126.             end
  9127.     end
  9128.  
  9129.     if @charid = 2      /*     cp850 has valid values from 0 to 255 */
  9130.     begin
  9131.             select @count = 32
  9132.             while @count <= 255
  9133.             begin
  9134.                 insert #helpsort1 (char_val)
  9135.                     values (char(@count))
  9136.                 select @count = @count + 1
  9137.             end
  9138.     end
  9139.  
  9140.     if @charid = 3      /*     cp437 has valid values from 0 to 255 */
  9141.     begin
  9142.             select @count =32
  9143.             while @count <= 255
  9144.             begin
  9145.                 insert #helpsort1 (char_val)
  9146.                     values (char(@count))
  9147.                 select @count = @count + 1
  9148.             end
  9149.     end
  9150.  
  9151.     if @charid = 4
  9152.         begin
  9153.                 select @count =32
  9154.                 while @count <= 255
  9155.                 begin
  9156.                         insert #helpsort1 (char_val)
  9157.                                 values (char(@count))
  9158.                         select @count = @count + 1
  9159.                 end
  9160.  
  9161.                 /* Remove unwanted values. (leih) 0x80(128) is now Euro Sign */
  9162.  
  9163.                 delete #helpsort1 where ascii(char_val) in (127, 129, 131, 136, 144, 152)
  9164.  
  9165.         end
  9166.  
  9167.     if @charid = 5
  9168.         begin
  9169.                 select @count =32
  9170.                 while @count <= 255
  9171.                 begin
  9172.                         insert #helpsort1 (char_val)
  9173.                                 values (char(@count))
  9174.                         select @count = @count + 1
  9175.                 end
  9176.  
  9177.                 /* Remove unwanted values. (leih) 0x88(136) is now Euro Sign */
  9178.  
  9179.                 delete #helpsort1 where ascii(char_val) in (127, 152)
  9180.  
  9181.         end
  9182.  
  9183.     if @charid = 6
  9184.         begin
  9185.                 select @count =32
  9186.                 while @count <= 255
  9187.                 begin
  9188.                         insert #helpsort1 (char_val)
  9189.                                 values (char(@count))
  9190.                         select @count = @count + 1
  9191.                 end
  9192.  
  9193.                 /* Remove unwanted values. (leih) 0x80(128) is now Euro Sign */
  9194.  
  9195.                 delete #helpsort1 where ascii(char_val) in (129, 136, 138, 140, 141, 142, 143, 144, 152, 154, 156, 157, 158, 159)
  9196.  
  9197.         end
  9198.  
  9199.     if @charid = 7
  9200.         begin
  9201.                 select @count =32
  9202.                 while @count <= 255
  9203.                 begin
  9204.                         insert #helpsort1 (char_val)
  9205.                                 values (char(@count))
  9206.                         select @count = @count + 1
  9207.                 end
  9208.  
  9209.                 /* Remove unwanted values. (leih) 0x80(128) is now Euro Sign */
  9210.  
  9211.                 delete #helpsort1 where ascii(char_val) in (129, 141, 142, 143, 144, 157, 158)
  9212.  
  9213.         end
  9214.  
  9215.     if @charid = 8
  9216.         begin
  9217.                 select @count =32
  9218.                 while @count <= 255
  9219.                 begin
  9220.                         insert #helpsort1 (char_val)
  9221.                                 values (char(@count))
  9222.                         select @count = @count + 1
  9223.                 end
  9224.  
  9225.                 /* Remove unwanted values. (leih) 0x80(128) is now Euro Sign  */
  9226.  
  9227.                 delete #helpsort1 where ascii(char_val) in (129, 138, 140, 141, 142, 143, 144, 154, 156, 157, 158, 159)
  9228.  
  9229.         end
  9230.  
  9231.     if @charid = 9
  9232.         begin
  9233.                 select @count =32
  9234.                 while @count <= 255
  9235.                 begin
  9236.                         insert #helpsort1 (char_val)
  9237.                                 values (char(@count))
  9238.                         select @count = @count + 1
  9239.                 end
  9240.  
  9241.                 /* Remove unwanted values. (leih) 0x80(128) is now Euro Sign  */
  9242.  
  9243.                 delete #helpsort1 where ascii(char_val) in (138, 143, 152, 154, 159)
  9244.  
  9245.         end
  9246.  
  9247.     if @charid = 10
  9248.         begin
  9249.                 select @count =32
  9250.                 while @count <= 255
  9251.                 begin
  9252.                         insert #helpsort1 (char_val)
  9253.                                 values (char(@count))
  9254.                         select @count = @count + 1
  9255.                 end
  9256.  
  9257.                 /* Remove unwanted values. (leih) 0x80(128) is now Euro Sign  */
  9258.  
  9259.                 delete #helpsort1 where ascii(char_val) in (129, 131, 136, 138, 140, 143, 144, 156, 159)
  9260.  
  9261.         end
  9262.  
  9263.  
  9264.     if @charid > 10     /* DBCS/User Character Set, not easy to display order.  Don't. */
  9265.     begin
  9266.         return (0)
  9267.     end
  9268.  
  9269.     select (char_val) into #helpsort2
  9270.         from #helpsort1
  9271.         order by char_val
  9272.  
  9273.     declare @char char(1)
  9274.     declare @char_str varchar(20)
  9275.     declare @incr int
  9276.     declare @seq_num int
  9277.     declare @rel char(1)
  9278.     declare @old_char char(1)
  9279.  
  9280.     select @char = char(0), @seq_num = 0, @count = 0, @incr = 8, @end_flag = 1
  9281.     select @rel = ' ', @old_char = NULL
  9282.  
  9283.     set rowcount 1
  9284.  
  9285.     while @end_flag <> 0
  9286.     begin
  9287.         select @char_str = ' '
  9288.  
  9289.         /* If PST_NOTUNIQ is set, then possibly caseless */
  9290.         if (@status & 8 = 8)
  9291.             while (@count < @incr  and  @end_flag <> 0)
  9292.             begin
  9293.                 select @char = char_val
  9294.                     from #helpsort2
  9295.                     where char_val >= @char
  9296.                 select @end_flag = @@rowcount
  9297.  
  9298.         if (@end_flag <> 0)
  9299.         begin
  9300.             if (@char = @old_char)
  9301.             select @rel = '='
  9302.             else
  9303.             select @rel = ' '
  9304.  
  9305.             select @old_char = @char
  9306.             select @char_str = @char_str + @rel + @char
  9307.             delete from #helpsort2 where ascii(@char) = ascii(char_val)
  9308.  
  9309.             select @count = @count + 1
  9310.         end
  9311.     end
  9312.     else
  9313.         while (@count < @incr  and  @end_flag <> 0)
  9314.             begin
  9315.                 select @char = char_val
  9316.                     from #helpsort2
  9317.                     where char_val > @char
  9318.                 select @end_flag = @@rowcount
  9319.                 if (@end_flag <> 0)
  9320.                     begin
  9321.                         select @char_str = @char_str + @rel + @char
  9322.                         delete from #helpsort2 where ascii(@char) = ascii(char_val)
  9323.                         select @count = @count + 1
  9324.                     end
  9325.             end
  9326.  
  9327.         select @incr = @incr + 8, @seq_num = @seq_num + 1
  9328.         insert master.dbo.spt_values (name, number, type, low, high)
  9329.         values (@char_str, @seq_num, 'Z', @charid, @sortid)
  9330.     end
  9331.  
  9332.     set rowcount 0
  9333.  
  9334. END
  9335.  
  9336. /*
  9337. ** Display the sorted list of characters.
  9338. */
  9339. select @count = 1
  9340. select @end_flag = 1
  9341. select @incr = 5
  9342.  
  9343. truncate table #helpsort3
  9344.  
  9345. while @end_flag <> 0
  9346. BEGIN
  9347.     select @string = ' '
  9348.  
  9349.     while @count < @incr
  9350.     begin
  9351.         select @string = @string + isnull(substring(name, 2, 19),'')
  9352.             from master.dbo.spt_values
  9353.             where type = 'Z'
  9354.                 and number = @count
  9355.                 and high = @sortid
  9356.         select @end_flag = @@rowcount
  9357.         select @count = @count + 1
  9358.     end
  9359.  
  9360.     select @incr = @incr + 4
  9361.  
  9362.     insert into #helpsort3 values (@string)
  9363. END
  9364.  
  9365. select 'Characters, in Order' = string
  9366.     from #helpsort3
  9367.  
  9368. set nocount off
  9369. return(0) -- sp_helpsort
  9370. go
  9371.  
  9372.  
  9373. checkpoint
  9374. go
  9375.  
  9376.  
  9377. raiserror(15339,-1,-1,'sp_helpsql')
  9378. go
  9379.  
  9380. create procedure sp_helpsql
  9381. @in_command varchar(30) = NULL
  9382. AS
  9383. print "SP_HELPSQL is not supported in this release, please refer to Online Help."
  9384. return(0)
  9385. go
  9386.  
  9387.  
  9388. raiserror(15339,-1,-1,'sp_monitor')
  9389. go
  9390. create procedure sp_monitor --- 1996/04/08 00:00
  9391. as
  9392.  
  9393. /*
  9394. **  Declare variables to be used to hold current monitor values.
  9395. */
  9396. declare @now         datetime
  9397. declare @cpu_busy     int
  9398. declare @io_busy    int
  9399. declare @idle        int
  9400. declare @pack_received    int
  9401. declare @pack_sent    int
  9402. declare @pack_errors    int
  9403. declare @connections    int
  9404. declare @total_read    int
  9405. declare @total_write    int
  9406. declare @total_errors    int
  9407.  
  9408. declare @oldcpu_busy     int    /* used to see if DataServer has been rebooted */
  9409. declare @interval    int
  9410. declare @mspertick    int    /* milliseconds per tick */
  9411.  
  9412. /*
  9413. **  If we're in a transaction, disallow this since it might make recovery
  9414. **  impossible.
  9415. */
  9416. set implicit_transactions off
  9417. if @@trancount > 0
  9418.     begin
  9419.         raiserror(15002,-1,-1,'sp_monitor')
  9420.         return (1)
  9421.     end
  9422.  
  9423. /*
  9424. **  Set @mspertick.  This is just used to make the numbers easier to handle
  9425. **  and avoid overflow.
  9426. */
  9427. select @mspertick = convert(int, @@timeticks / 1000.0)
  9428.  
  9429. /*
  9430. **  Get current monitor values.
  9431. */
  9432. select
  9433.     @now = getdate(),
  9434.     @cpu_busy = @@cpu_busy,
  9435.     @io_busy = @@io_busy,
  9436.     @idle = @@idle,
  9437.     @pack_received = @@pack_received,
  9438.     @pack_sent = @@pack_sent,
  9439.     @connections = @@connections,
  9440.     @pack_errors = @@packet_errors,
  9441.     @total_read = @@total_read,
  9442.     @total_write = @@total_write,
  9443.     @total_errors = @@total_errors
  9444.  
  9445. /*
  9446. **  Check to see if DataServer has been rebooted.  If it has then the
  9447. **  value of @@cpu_busy will be less than the value of spt_monitor.cpu_busy.
  9448. **  If it has update spt_monitor.
  9449. */
  9450. select @oldcpu_busy = cpu_busy
  9451.     from master.dbo.spt_monitor
  9452. if @oldcpu_busy > @cpu_busy
  9453. begin
  9454.     update master.dbo.spt_monitor
  9455.         set
  9456.             lastrun = @now,
  9457.             cpu_busy = @cpu_busy,
  9458.             io_busy = @io_busy,
  9459.             idle = @idle,
  9460.             pack_received = @pack_received,
  9461.             pack_sent = @pack_sent,
  9462.             connections = @connections,
  9463.             pack_errors = @pack_errors,
  9464.             total_read = @total_read,
  9465.             total_write = @total_write,
  9466.             total_errors = @total_errors
  9467. end
  9468.  
  9469. /*
  9470. **  Now print out old and new monitor values.
  9471. */
  9472. set nocount on
  9473. select @interval = datediff(ss, lastrun, @now)
  9474.     from master.dbo.spt_monitor
  9475. /* To prevent a divide by zero error when run for the first
  9476. ** time after boot up
  9477. */
  9478. if @interval = 0
  9479.     select @interval = 1
  9480. select last_run = lastrun, current_run = @now, seconds = @interval
  9481.     from master.dbo.spt_monitor
  9482.  
  9483. select
  9484.     cpu_busy = substring(convert(varchar(11),
  9485.         convert(int, ((@cpu_busy * @mspertick) / 1000)))
  9486.         + '('
  9487.         + convert(varchar(11), convert(int, (((@cpu_busy - cpu_busy)
  9488.         * @mspertick) / 1000)))
  9489.         + ')'
  9490.         + '-'
  9491.         + convert(varchar(11), convert(int, ((((@cpu_busy - cpu_busy)
  9492.         * @mspertick) / 1000) * 100) / @interval))
  9493.         + '%',
  9494.         1, 25),
  9495.     io_busy = substring(convert(varchar(11),
  9496.         convert(int, ((@io_busy * @mspertick) / 1000)))
  9497.         + '('
  9498.         + convert(varchar(11), convert(int, (((@io_busy - io_busy)
  9499.         * @mspertick) / 1000)))
  9500.         + ')'
  9501.         + '-'
  9502.         + convert(varchar(11), convert(int, ((((@io_busy - io_busy)
  9503.         * @mspertick) / 1000) * 100) / @interval))
  9504.         + '%',
  9505.         1, 25),
  9506.     idle = substring(convert(varchar(11),
  9507.         convert(int, ((@idle * @mspertick) / 1000)))
  9508.         + '('
  9509.         + convert(varchar(11), convert(int, (((@idle - idle)
  9510.         * @mspertick) / 1000)))
  9511.         + ')'
  9512.         + '-'
  9513.         + convert(varchar(11), convert(int, ((((@idle - idle)
  9514.         * @mspertick) / 1000) * 100) / @interval))
  9515.         + '%',
  9516.         1, 25)
  9517. from master.dbo.spt_monitor
  9518.  
  9519. select
  9520.     packets_received = substring(convert(varchar(11), @pack_received) + '(' +
  9521.         convert(varchar(11), @pack_received - pack_received) + ')', 1, 25),
  9522.     packets_sent = substring(convert(varchar(11), @pack_sent) + '(' +
  9523.         convert(varchar(11), @pack_sent - pack_sent) + ')', 1, 25),
  9524.     packet_errors = substring(convert(varchar(11), @pack_errors) + '(' +
  9525.         convert(varchar(11), @pack_errors - pack_errors) + ')', 1, 25)
  9526. from master.dbo.spt_monitor
  9527.  
  9528. select
  9529.     total_read = substring(convert(varchar(11), @total_read) + '(' +
  9530.         convert(varchar(11), @total_read - total_read) + ')', 1, 19),
  9531.     total_write = substring(convert(varchar(11), @total_write) + '(' +
  9532.         convert(varchar(11), @total_write - total_write) + ')', 1, 19),
  9533.     total_errors = substring(convert(varchar(11), @total_errors) + '(' +
  9534.         convert(varchar(11), @total_errors - total_errors) + ')', 1, 19),
  9535.     connections = substring(convert(varchar(11), @connections) + '(' +
  9536.         convert(varchar(11), @connections - connections) + ')', 1, 18)
  9537. from master.dbo.spt_monitor
  9538.  
  9539. /*
  9540. **  Now update spt_monitor
  9541. */
  9542. update master.dbo.spt_monitor
  9543.     set
  9544.         lastrun = @now,
  9545.         cpu_busy = @cpu_busy,
  9546.         io_busy = @io_busy,
  9547.         idle = @idle,
  9548.         pack_received = @pack_received,
  9549.         pack_sent = @pack_sent,
  9550.         connections = @connections,
  9551.         pack_errors = @pack_errors,
  9552.         total_read = @total_read,
  9553.         total_write = @total_write,
  9554.         total_errors = @total_errors
  9555.  
  9556. return (0) -- sp_monitor
  9557. go
  9558.  
  9559. raiserror(15339,-1,-1,'sp_processmail')
  9560. go
  9561. create procedure sp_processmail --- 1996/06/19 17:30
  9562.     @subject varchar(255)=NULL,
  9563.     @filetype varchar(3)='txt',
  9564.     @separator varchar(3)='tab',
  9565.     @set_user sysname='guest',
  9566.     @dbuse sysname='master'
  9567. as
  9568.  
  9569. declare @status int
  9570. declare @msg_id varchar(64)
  9571. declare @originator varchar(255)
  9572. declare @cc_list varchar(255)
  9573. declare @msgsubject varchar(255)
  9574. declare @query varchar(255)
  9575. declare @messages int
  9576. declare @mapifailure int
  9577. declare @resultmsg varchar(80)
  9578. declare @filename varchar(12)
  9579. declare @current_msg varchar(64)
  9580.  
  9581. select @messages=0
  9582. select @mapifailure=0
  9583.  
  9584. if @separator='tab' select @separator=CHAR(9)
  9585.  
  9586. /* get first message id */
  9587. exec @status = master.dbo.xp_findnextmsg
  9588.         @msg_id=@msg_id output,
  9589.         @unread_only='true'
  9590.  
  9591. if @status <> 0
  9592.     select @mapifailure=1
  9593.  
  9594. while (@mapifailure=0)
  9595.   begin
  9596.  
  9597.     if @msg_id is null break
  9598.     if @msg_id = '' break
  9599.  
  9600.     exec @status = master.dbo.xp_readmail
  9601.         @msg_id=@msg_id,
  9602.         @originator=@originator output,
  9603.         @cc_list=@cc_list output,
  9604.         @subject=@msgsubject output,
  9605.         @message=@query output,
  9606.         @peek='true',
  9607.  
  9608.         @suppress_attach='true'
  9609.  
  9610.     if @status <> 0
  9611.     begin
  9612.         select @mapifailure=1
  9613.         break
  9614.     end
  9615.  
  9616.     /* get new message id before processing & deleting current */
  9617.     select @current_msg=@msg_id
  9618.     exec @status = master.dbo.xp_findnextmsg
  9619.         @msg_id=@msg_id output,
  9620.         @unread_only='true'
  9621.  
  9622.         if @status <> 0
  9623.     begin
  9624.         select @mapifailure=1
  9625.  
  9626.         break
  9627.     end
  9628.  
  9629.  
  9630.     if ((@subject IS NULL) OR (@subject=@msgsubject))
  9631.     begin
  9632.     /* generate random filename */
  9633.     select @filename='SQL' + convert(varchar,ROUND(RAND()*100000,0)) + '.' + @filetype
  9634.  
  9635.     exec @status = master.dbo.xp_sendmail
  9636.             @recipients=@originator,
  9637.             @copy_recipients=@cc_list,
  9638.             @message=@query,
  9639.             @query=@query,
  9640.             @subject='Query Results',
  9641.             @separator=@separator,
  9642.             @width=256,
  9643.             @attachments=@filename,
  9644.             @attach_results='true',
  9645.             @no_output='false',
  9646.             @echo_error='true',
  9647.             @set_user=@set_user,
  9648.             @dbuse=@dbuse
  9649.  
  9650.     if @status <> 0
  9651.         begin
  9652.             select @mapifailure=1
  9653.             break        
  9654.         end
  9655.     
  9656.     select @messages=@messages+1
  9657.  
  9658.     exec master.dbo.xp_deletemail @current_msg
  9659.  
  9660.     end /* end of xp_sendmail block */
  9661.   end  /* end of xp_findnextmsg loop */
  9662.  
  9663.   /* finished examining the contents of inbox;  now send results */
  9664.   if @mapifailure=0
  9665.           begin
  9666.         raiserror(15079,-1,-1,@messages)
  9667.         return(1)
  9668.     end
  9669.   else    
  9670.     return(0)
  9671. -- sp_processmail
  9672. go
  9673.  
  9674.  
  9675. raiserror(15339,-1,-1,'sp_recompile')
  9676. go
  9677. create procedure sp_recompile
  9678.     @objname         nvarchar(776)
  9679. as
  9680.     -- do sets and declares
  9681.     Set nocount on
  9682.     declare @objid      int,
  9683.             @curdbname  sysname
  9684.  
  9685.     -- CHECK VALIDITY OF OBJECT NAME --
  9686.     --  (1) Must exist in current database
  9687.     --  (2) Must be a table or an executable object
  9688.     select @objid = object_id(@objname, 'local')
  9689.     if @objid is null OR
  9690.         (ObjectProperty(@objid, 'IsTable') = 0 AND
  9691.          ObjectProperty(@objid, 'IsExecuted') = 0)
  9692.     begin
  9693.         select @curdbname = db_name()
  9694.         raiserror(15009,-1,-1 ,@objname, @curdbname)
  9695.         return @@error
  9696.     end
  9697.  
  9698.     -- CHECK PERMISSION --
  9699.     if (is_member('db_owner') = 0) AND (is_member('db_ddladmin') = 0)
  9700.         AND (is_member(user_name(ObjectProperty(@objid, 'ownerid'))) = 0)
  9701.     begin
  9702.         raiserror(15219,-1,-1,@objname)
  9703.         return @@error
  9704.     end
  9705.  
  9706.     -- BUMP SCHEMA FOR RECOMPILE --
  9707.     DBCC LockObjectSchema(@objname)
  9708.     if @@error <> 0
  9709.         return (1)
  9710.  
  9711.     -- TH-TH-TH-THAT'S IT!
  9712.     raiserror(15070,-1,-1,@objname)
  9713.     return (0) -- sp_recompile
  9714. go
  9715.  
  9716. checkpoint
  9717. go
  9718.  
  9719. raiserror(15339,-1,-1,'sp_remoteoption')
  9720. go
  9721. create procedure sp_remoteoption --- 1996/04/08 00:00
  9722.     @remoteserver sysname = NULL,    /* server name to change */
  9723.     @loginame sysname = NULL,        /* user's remote name */
  9724.     @remotename sysname = NULL,        /* user's local user name */
  9725.     @optname varchar(35) = NULL,        /* option name to turn on/off */
  9726.     @optvalue varchar(10) = NULL        /* true or false */
  9727. as
  9728.     declare @optcount int            /* number of options like @optname */
  9729.     declare @sid    varbinary(85)
  9730.  
  9731.     -- NO SERVER NAME? SHOW SETTABLE OPTION ('trusted')
  9732.     if @remoteserver is null
  9733.     begin
  9734.         raiserror(15473,-1,-1)
  9735.         select remotelogin_option = name from master.dbo.spt_values
  9736.             where type = 'F_U' and number = 16
  9737.         return (0)
  9738.     end
  9739.  
  9740.     -- NO USER XACT --
  9741.     set implicit_transactions off
  9742.     if @@trancount > 0
  9743.     begin
  9744.         raiserror(15002,-1,-1,'sp_remoteoption')
  9745.         return (1)
  9746.     end
  9747.  
  9748.     -- PERMISSIONS --
  9749.     if not (is_srvrolemember('securityadmin') = 1)
  9750.     begin
  9751.         raiserror(15474,-1,-1)
  9752.         return (1)
  9753.     end
  9754.  
  9755.     -- VALIDATE SERVER NAME --
  9756.     declare @srvid smallint
  9757.     select @srvid = srvid from master.dbo.sysservers where srvname = @remoteserver
  9758.     if @srvid is null
  9759.     begin
  9760.         raiserror(15015,-1,-1,@remoteserver)
  9761.         return (1)
  9762.     end
  9763.  
  9764.     -- VALIDATE @loginame --
  9765.     if @loginame is not null
  9766.     begin
  9767.         select @sid = sid from master.dbo.syslogins where loginname = @loginame
  9768.                     AND isntname = 0        -- cannot remap to NT login
  9769.         if @sid is null
  9770.         begin
  9771.             raiserror(15067,-1,-1,@loginame)
  9772.             return (1)
  9773.         end
  9774.     end
  9775.  
  9776.     -- VALIDATE <@sid, @remotename> PAIR FOR @srvid --
  9777.     if not exists (select * from master.dbo.sysxlogins where srvid = @srvid
  9778.                 and ((@remotename is null AND name is null) OR name = @remotename)
  9779.                 and ((@sid is null AND sid is null) OR sid = @sid))
  9780.     begin
  9781.         raiserror(15185,-1,-1,@remotename,@loginame,@remoteserver)
  9782.         return (1)
  9783.     end
  9784.  
  9785.     -- Check remaining parameters --
  9786.     if @optname is NULL or lower(@optvalue) not in ('true', 'false') or @optvalue = null
  9787.     begin
  9788.         raiserror(15220,-1,-1)
  9789.         return (1)
  9790.     end
  9791.  
  9792.     -- SEE IF @optname MATCHES THE 'trusted' OPTION --
  9793.     if not exists (select * from master.dbo.spt_values where name like '%' + @optname + '%'
  9794.             and type = 'F_U' and number = 16)
  9795.     begin
  9796.         raiserror(15221,-1,-1)
  9797.         return (1)
  9798.     end
  9799.  
  9800.     -- Now update sysremotelogins
  9801.     if lower(@optvalue) = 'true'
  9802.     begin
  9803.         update master.dbo.sysxlogins set xstatus = xstatus | 16, xdate1 = getdate()
  9804.             where srvid = @srvid
  9805.                 and ((@remotename is null AND name is null) OR name = @remotename)
  9806.                 and ((@sid is null AND sid is null) OR sid = @sid)
  9807.         raiserror(15517,-1,-1,@optname)
  9808.     end
  9809.     else    -- 'false'
  9810.     begin
  9811.         update master.dbo.sysxlogins set xstatus = xstatus & ~16, xdate1 = getdate()
  9812.             where srvid = @srvid
  9813.                 and ((@remotename is null AND name is null) OR name = @remotename)
  9814.                 and ((@sid is null AND sid is null) OR sid = @sid)
  9815.         raiserror(15518,-1,-1,@optname)
  9816.     end
  9817.     return (0) -- sp_remoteoption
  9818. go
  9819.  
  9820. checkpoint
  9821. go
  9822.  
  9823. raiserror(15339,-1,-1,'sp_tableoption')
  9824. go
  9825. /*ANSI_NULLS on for creation of sp_tableoption*/
  9826. Set ansi_nulls on
  9827. go
  9828. create procedure sp_tableoption  --- 1996/09/09 14:17
  9829.     @TableNamePattern      ncharacter varying(776)
  9830.  
  9831.    ,@OptionName            character varying(35)   = null
  9832.    ,@OptionValue           character varying(12)   = null
  9833. as
  9834.  
  9835. Set nocount       on
  9836. Set ansi_warnings on
  9837.  
  9838. Declare @exec_stmt nvarchar(975)
  9839.  
  9840. Declare
  9841.        @RetCode            integer
  9842.       ,@int1               integer
  9843. Declare
  9844.        @CurrentDBName      sysname
  9845.       ,@CurrentDBId        integer
  9846.       ,@CountMatchedObj    integer
  9847.       ,@CountUpdRows2      integer
  9848.       ,@IRLString          varchar(35)
  9849.       ,@BCPTabLockString   varchar(35)
  9850.       ,@PinTabString       varchar(35)
  9851.       ,@Status_csr_11      integer
  9852.       ,@TabId              integer
  9853.       ,@BitLogic           varchar(9)
  9854. Declare
  9855.        @WOptionName        character varying(35)  -- spt_values.name
  9856.       ,@WOptionNum         integer
  9857.       ,@charWOptionNum     varchar(12)
  9858.       ,@WOptionValue       character varying( 6)  -- T/F
  9859.       ,@intOptionValue     integer
  9860. Declare
  9861.        @UnqualName         sysname
  9862.       ,@QualName1          sysname    -- own
  9863.       ,@QualName2          sysname    -- db
  9864.       ,@QualName3          sysname    -- svr
  9865.  
  9866.       ,@WQualName1         sysname
  9867.       ,@WQualName2         sysname
  9868.  
  9869. /*Create temp tables before any DML to ensure dynamic*/
  9870. CREATE table #t1
  9871.    (
  9872.     ObjId          integer     not null
  9873.    ,CurrentValues  integer     not null
  9874.    )
  9875. CREATE unique
  9876.    index    ix2
  9877.    on       #t1   (ObjId)
  9878.  
  9879. -----------------------------
  9880.  
  9881. Select
  9882.        @RetCode            = 0   --  =0 is good,  >0 is bad.
  9883.       ,@CurrentDBName      = db_name()
  9884.       ,@CurrentDBId        = db_id()
  9885.       ,@CountMatchedObj    = 0
  9886.       ,@CountUpdRows2      = 0
  9887.       ,@IRLString          = 'insert row lock'
  9888.       ,@BCPTabLockString   = 'table lock on bulk load'
  9889.       ,@PinTabString       = 'pintable'
  9890.       ,@Status_csr_11      = 0  -- 0x01 bit =Declared; 0x02 bit =Open.
  9891.       ,@TabId              = null
  9892. Select
  9893.        @UnqualName         = null
  9894.       ,@QualName1          = null
  9895.       ,@QualName2          = null
  9896.       ,@QualName3          = null
  9897.  
  9898.       ,@WQualName1         = null  -- own
  9899.       ,@WQualName2         = null  -- db
  9900.  
  9901.  
  9902. --------------------- Basic parm edits  -------------------
  9903.  
  9904. IF (@TableNamePattern IS null)
  9905.    begin
  9906.    raiserror(15223,-1,-1,'@TableNamePattern')
  9907.    Select @RetCode = @@error
  9908.    GOTO LABEL_86_RETURN
  9909.    end
  9910.  
  9911. IF (@OptionName is null)
  9912.    begin
  9913.    ------- Report, then bye.
  9914.  
  9915.    SELECT
  9916.                    val.name   as 'Available Table Options'
  9917.                   ,val.status as 'Default Value'
  9918.          from      master.dbo.spt_values  val
  9919.          where     val.type   = 'TBO'
  9920.          and       val.number > 0
  9921.          order by  val.name
  9922.  
  9923.    GOTO LABEL_86_RETURN
  9924.  
  9925.    end
  9926.  
  9927.  
  9928. --------  Gather spt_values info (only tab opts with 'TBO' rows are docu).
  9929.  
  9930.  
  9931. SELECT
  9932.              @WOptionName        = min(val.name)
  9933.             ,@WOptionNum         = min(val.number)
  9934.             ,@int1               = count(*)
  9935.       from   master.dbo.spt_values  val
  9936.       where  val.type            = 'TBO'
  9937.       and    val.number          > 0
  9938.       and    lower(val.name) like (lower(@OptionName) + '%')
  9939.  
  9940. IF (@int1 <> 1)
  9941.    begin
  9942.    raiserror(15386,-1,-1,@OptionName,@int1)
  9943.    Select @RetCode = @@error
  9944.    GOTO LABEL_86_RETURN
  9945.    end
  9946.  
  9947. Select @charWOptionNum = convert(varchar,@WOptionNum)
  9948.  
  9949.  
  9950. -------- Parse apart the perhaps dots-qualified name.  ---------------
  9951.  
  9952. -- get name parts --
  9953. select @UnqualName = parsename(@TableNamePattern, 1),
  9954.         @QualName1 = parsename(@TableNamePattern, 2),
  9955.         @QualName2 = parsename(@TableNamePattern, 3),
  9956.         @QualName3 = parsename(@TableNamePattern, 4)
  9957.  
  9958. IF (@UnqualName is NULL OR @QualName3 is not null)
  9959.    begin
  9960.    raiserror(15253,-1,-1,@TableNamePattern)
  9961.    Select @RetCode = @@error
  9962.    GOTO LABEL_86_RETURN
  9963.    end
  9964.  
  9965.  
  9966. ------------------  Verify database.
  9967.  
  9968.  
  9969. Select @WQualName2 = @QualName2
  9970.  
  9971. IF (@WQualName2 is null)
  9972.    begin
  9973.    Select @WQualName2 = @CurrentDBName
  9974.    end
  9975.  
  9976. IF (@WQualName2 <> @CurrentDBName)
  9977.    begin
  9978.    raiserror(15387,-1,-1)
  9979.    Select @RetCode = @@error
  9980.    GOTO LABEL_86_RETURN
  9981.    end
  9982.  
  9983.  
  9984. ------------------  Settle owner.
  9985.  
  9986.  
  9987. Select @WQualName1 = @QualName1
  9988.  
  9989. IF (@WQualName1 is null)  -- Owner not part of any qualification.
  9990.    begin
  9991.    Select @WQualName1 = user_name()  -- '%' might not be intuitive.
  9992.    end
  9993.  
  9994.  
  9995. ------------------  Are zero objects matched?
  9996.  
  9997.  
  9998. SELECT          @CountMatchedObj = count(*)
  9999.       from      sysobjects       sysobj
  10000.       where     sysobj.xtype      = 'U '
  10001.       and       user_name(sysobj.uid) = @WQualName1
  10002.       and       sysobj.name           = @UnqualName
  10003.  
  10004. IF (@CountMatchedObj = 0)
  10005.    begin
  10006.    raiserror(15388,-1,-1,@TableNamePattern)
  10007.    Select @RetCode = @@error
  10008.    GOTO LABEL_86_RETURN
  10009.    end
  10010.  
  10011.  
  10012. -------------  Project any option info into one common format/location.  -----
  10013.  
  10014. IF (@WOptionName in (@BCPTabLockString, @PinTabString))
  10015.    begin
  10016.  
  10017.    INSERT into #t1
  10018.          (ObjId ,CurrentValues)
  10019.       SELECT
  10020.                 sysobj.id  ,sysobj.status
  10021.          from
  10022.                 sysobjects       sysobj
  10023.          where
  10024.                 sysobj.xtype      = 'U '
  10025.          and    user_name(sysobj.uid)  = @WQualName1
  10026.          and    sysobj.name            = @UnqualName
  10027.    end
  10028.  
  10029.  
  10030. -----------------  Was option value parm specified?  ---------------
  10031.  
  10032.  
  10033. Select @WOptionValue = lower(@OptionValue)
  10034.  
  10035.  
  10036. IF (@OptionValue is null)
  10037.    begin
  10038.    --    Report current option settings, then bye.
  10039.  
  10040.    SELECT
  10041.                 CASE
  10042.                   When t1.CurrentValues & @WOptionNum <> 0 Then 'True '
  10043.                   When t1.CurrentValues & @WOptionNum  = 0 Then 'False'
  10044.                 END
  10045.                               as 'Option Status'
  10046.                ,@UnqualName   as 'Table Name'
  10047.                ,@WQualName1
  10048.                               as 'Owner Name'
  10049.          from
  10050.                 #t1           t1
  10051.          order by
  10052.                 1 ,2 ,3
  10053.  
  10054.  
  10055.    GOTO LABEL_86_RETURN
  10056.  
  10057.    end
  10058.  
  10059.  
  10060. IF (@WOptionValue in ('1' ,'on' ,'yes'))
  10061.    begin
  10062.    Select @WOptionValue  = 'true'
  10063.    end
  10064.  
  10065. IF (@WOptionValue in ('0' ,'off' ,'no'))
  10066.    begin
  10067.    Select @WOptionValue  = 'false'
  10068.    end
  10069.  
  10070.  
  10071. IF (@WOptionValue not in ('true','false'))
  10072.    begin
  10073.    raiserror(15389,-1,-1,@OptionValue)
  10074.    Select @RetCode = @@error
  10075.    GOTO LABEL_86_RETURN
  10076.    end
  10077.  
  10078. Select @intOptionValue =
  10079.             CASE @WOptionValue
  10080.                When 'true'  Then 1
  10081.                When 'false' Then 0
  10082.             END
  10083.  
  10084. --------------------------  Security  ------------------
  10085.  
  10086.  
  10087. IF (@WOptionName = @PinTabString)
  10088.    begin
  10089.  
  10090.    IF (not (is_srvrolemember('serveradmin') = 1))
  10091.       begin
  10092.       raiserror(15392,-1,-1,@WOptionName)
  10093.       Select @RetCode = @@error
  10094.       GOTO LABEL_86_RETURN
  10095.       end
  10096.    end
  10097.  
  10098.  
  10099. --SA & DBO generally have no security restrictions.
  10100. IF not (is_member('db_owner') = 1) and
  10101.     not (is_member('db_ddladmin') = 1)
  10102.    begin
  10103.    IF (is_member(@WQualName1) <> 1)    ---- nonSA/nonDBO users can only affect their own tables.
  10104.       begin
  10105.       raiserror(15390,-1,-1,@WOptionName)
  10106.       Select @RetCode = @@error
  10107.       GOTO LABEL_86_RETURN
  10108.       end
  10109.    end
  10110.  
  10111.  
  10112. /*
  10113. **No-opt for  IRL
  10114. */
  10115. IF @WOptionName = @IRLString
  10116.         GOTO LABEL_75_FINAL
  10117.  
  10118. ------------------  Prepare cursor  -------------------------
  10119.  
  10120.  
  10121. IF (@intOptionValue = 0)    --Want it False,
  10122.    begin
  10123.    Select @BitLogic = ' <> '   --but is True  currently.
  10124.    end
  10125. ELSE                        --Want it True,
  10126.    begin
  10127.    Select @BitLogic = '  = '   --but is False currently.
  10128.    end
  10129.  
  10130. select @exec_stmt = '
  10131. DECLARE         csr_11_tabid
  10132.                 insensitive
  10133.             cursor for
  10134.    SELECT
  10135.                 t1.ObjId
  10136.          from   #t1           t1
  10137.          where  
  10138.                 t1.CurrentValues & ' + @charWOptionNum + ' ' + @BitLogic + ' 0
  10139. '
  10140. EXECUTE(@exec_stmt)
  10141. Select @Status_csr_11 = 1
  10142.  
  10143. Open csr_11_tabid
  10144. Select @Status_csr_11 = @Status_csr_11 | 2
  10145.  
  10146.  
  10147. WHILE (11=11)
  10148.    begin
  10149.  
  10150.    FETCH    next from csr_11_tabid
  10151.          into
  10152.                 @TabId
  10153.  
  10154.    IF (@@fetch_status <> 0)
  10155.       begin
  10156.       Deallocate csr_11_tabid
  10157.       Select @Status_csr_11 = 0
  10158.       BREAK
  10159.       end
  10160.  
  10161.    Select @CountUpdRows2 = @CountUpdRows2 + 1
  10162.  
  10163.    IF (@WOptionName in (@BCPTabLockString))
  10164.       begin
  10165.       DBCC bcptablock(@CurrentDBId,@TabId,@intOptionValue) -- (objinfo.h)
  10166.       end
  10167.  
  10168.    IF (@WOptionName in (@PinTabString))
  10169.       begin
  10170.       IF (@intOptionValue = 0)
  10171.          begin
  10172.          DBCC unpintable(@CurrentDBId,@TabId)
  10173.          end
  10174.       ELSE
  10175.          begin
  10176.          DBCC   pintable(@CurrentDBId,@TabId)
  10177.          end
  10178.       end
  10179.  
  10180.    end --loop 11
  10181.  
  10182.  
  10183. -----------------  Finalization  -------------------------
  10184.  
  10185.  
  10186. LABEL_75_FINAL:
  10187.  
  10188. Raiserror(15391,-1,-1,@CountMatchedObj,@WOptionName,@OptionValue,@CountUpdRows2)
  10189.  
  10190. LABEL_86_RETURN:
  10191.  
  10192. IF (@Status_csr_11 > 0)
  10193.    begin
  10194.    Deallocate csr_11
  10195.    end
  10196.  
  10197. IF (object_id('tempdb..#t1') is not null)
  10198.    begin
  10199.             drop table #t1
  10200.    end
  10201.  
  10202. Return @RetCode  --sp_tableoption
  10203. go
  10204. Set ansi_nulls off
  10205. go
  10206. /*ANSI_NULLS off for after creation of sp_tableoption*/
  10207.  
  10208. checkpoint
  10209. go
  10210.  
  10211. raiserror(15339,-1,-1,'sp_procoption')
  10212. go
  10213. /*ANSI_NULLS on for  creation of sp_procoption*/
  10214. Set ansi_nulls on
  10215. go
  10216. create procedure sp_procoption  --- 1996/09/09 14:17
  10217.     @ProcName               ncharacter varying(776)  = null    -- NO PATTERN MATCHING
  10218.  
  10219.    ,@OptionName            character varying(35)   = null
  10220.    ,@OptionValue           character varying(12)   = null
  10221. as
  10222.  
  10223. Set nocount       on
  10224. Set ansi_warnings on
  10225.  
  10226. Declare
  10227.     @_trancount        integer
  10228.     ,@int1                integer
  10229. Declare
  10230.     @CountUpdRows2        integer
  10231.     ,@StartUpString        varchar(35)
  10232. Declare
  10233.     @BitOptStatic        integer  --- spt_values.status 'PRO'
  10234.     ,@BitOptTypeP        integer
  10235.     ,@BitOptTypeX        integer
  10236. Declare
  10237.     @WOptionName        character varying(35)  -- spt_values.name
  10238.     ,@WOptionNum        integer
  10239.     ,@WOptionValue        character varying( 6)  -- T/F
  10240.     ,@WOptionStatus        integer
  10241. Declare    
  10242.     @ObjId                integer
  10243.     ,@OwnUId            smallint
  10244.     ,@ObjType            character(2)
  10245.     ,@Status            integer
  10246. Declare 
  10247.     @autoproc_statbit    integer
  10248.     ,@cAutoProc            integer
  10249.  
  10250.  
  10251. /*    Initialize Vars    */
  10252. Select
  10253.     @_trancount            = @@trancount
  10254.     ,@CountUpdRows2        = 0
  10255.     ,@StartUpString        = 'startup'
  10256. Select
  10257.     @BitOptStatic        = 0x100
  10258.     ,@BitOptTypeP        = 0x1
  10259.     ,@BitOptTypeX        = 0x2
  10260.     ,@WOptionName        = null
  10261. Select @autoproc_statbit = min(number) from master.dbo.spt_values 
  10262.     where type='PRO' and name ='startup'
  10263. Select @cAutoProc = count(*) from sysobjects 
  10264.     where type in ('X','P') and (status & @autoproc_statbit = @autoproc_statbit)
  10265.  
  10266. IF (@ProcName is null) and (@OptionName is null)
  10267.    begin
  10268.    /* Report, then bye.*/
  10269.  
  10270.     SELECT
  10271.         val.name   as 'Available Proc Options'
  10272.         ,case val.status & @BitOptStatic
  10273.             when 0   then 'change-able' --- change-able
  10274.             else          'unchange-able'
  10275.         end  as 'Change-ability' --- Change-ability
  10276.  
  10277.         from      master.dbo.spt_values  val
  10278.         where     val.type   = 'PRO'
  10279.         and       val.number <> 0
  10280.         order by  val.name
  10281.  
  10282.     return (0)
  10283.  
  10284.    end
  10285.  
  10286.  
  10287. /*    Check valid option name    */
  10288. SELECT
  10289.              @WOptionName        = min(val.name)
  10290.             ,@WOptionNum         = min(val.number) -- Will/Must be followed by unity test, thus count(*).
  10291.             ,@WOptionStatus      = min(val.status)
  10292.       from   master.dbo.spt_values  val
  10293.       where  val.type            = 'PRO'
  10294.       and    val.number         <> 0
  10295.       and    lower(val.name) = (lower(@OptionName))
  10296.  
  10297. IF (@WOptionName is null)
  10298.    begin
  10299.        raiserror(15386,-1,20 ,@OptionName,0)
  10300.        return @@error
  10301.    end
  10302.  
  10303. IF (parsename(@ProcName,3) is not null and parsename(@ProcName,3) <> db_name())
  10304. begin
  10305.    raiserror(15387,-1,99)
  10306.    return @@error
  10307. end
  10308.  
  10309. /*    Get info for specified object    */
  10310. SELECT @ObjId = id, @OwnUId = uid, @Status = status, @ObjType = xtype
  10311.       from      sysobjects
  10312.       where     id = object_id(@ProcName)
  10313.       and       xtype in ('P ' ,'X ')
  10314.  
  10315. /*    Check that object exists    */
  10316. IF (@ObjId is null and @ProcName is not null)
  10317.    begin
  10318.        raiserror(15388,-1,88 ,@ProcName)
  10319.        return @@error
  10320.    end
  10321.  
  10322. /*    If @optionvalue null report @optionname settings on proc specified    */
  10323. /*    DOES NOT!!! USE pattern matching */
  10324. IF (@OptionValue is null)
  10325. begin
  10326.     SELECT
  10327.         CASE
  10328.             When status & @WOptionNum <> 0 Then 'True '
  10329.             When status & @WOptionNum  = 0 Then 'False'
  10330.         END                                                as 'Option Status'
  10331.     ,name                                                as 'Procedure Name'
  10332.     ,user_name(uid)                                        as 'Owner Name'
  10333.     ,xtype                                                as 'Proc Type'
  10334.  
  10335.     from sysobjects where (id = @ObjId or @ProcName is null)
  10336.                     and xtype in ('P ','X ')
  10337.     return (0)
  10338. end
  10339.  
  10340. /*    Make optionvalue case insensitive    */
  10341. Select @WOptionValue = lower(@OptionValue)
  10342.  
  10343. /* Check for valid optionvalue    */
  10344. Select @WOptionValue =
  10345.     case 
  10346.         when @WOptionValue in ('1' ,'on' ,'yes', 'true') then 'true'
  10347.         when @WOptionValue in ('0' ,'off' ,'no', 'false') then 'false'
  10348.         else null
  10349.     end
  10350.  
  10351. IF (@WOptionValue is null)
  10352.    begin
  10353.        raiserror(15389,-1,77 ,@OptionValue)
  10354.        return @@error
  10355.    end
  10356.  
  10357.  
  10358. /*    Check that option selected is static    */
  10359.  
  10360. IF (@WOptionStatus & @BitOptStatic <> 0)
  10361.    begin
  10362.        raiserror(15396,-1,48 ,@WOptionName)
  10363.        return @@error
  10364.    end
  10365.  
  10366. -------------------  Security (per option, more than Grants)  ----------------
  10367.  
  10368. IF (@WOptionName in (@StartUpString))
  10369.    begin
  10370.  
  10371.    IF (not (is_srvrolemember('setupadmin') = 1))
  10372.       begin
  10373.           raiserror(15392,-1,41 ,@WOptionName)
  10374.           return @@error
  10375.       end
  10376.  
  10377.    IF (@ProcName is null)
  10378.       begin
  10379.         raiserror(15397,-1,92 ,@WOptionName ,0)
  10380.         return @@error
  10381.       end
  10382.  
  10383.     -- STARTUP PROC MUST BE OWNED BY DBO IN MASTER!
  10384.    IF (db_id()  <> 1 OR @OwnUId <> 1)
  10385.       begin
  10386.         raiserror(15398,-1,80 ,@WOptionName)
  10387.         return @@error
  10388.       end
  10389.  
  10390.    IF Exists (SELECT * from syscolumns syscol where syscol.id= @ObjId)
  10391.       begin
  10392.         raiserror(15399,-1, 93 ,@WOptionName ,NULL)
  10393.         return @@error
  10394.       end
  10395.    end
  10396.  
  10397.  
  10398. -- CHECK PERMISSION --
  10399. -- MUST BE sysadmin (Startup-procs run as sysadmin) --
  10400. IF (is_srvrolemember('sysadmin') = 0)
  10401. begin
  10402.     raiserror(15390,-1,6 ,@WOptionName)
  10403.     return @@error
  10404. end
  10405.  
  10406. /*        If want it False and currently true  or    */
  10407. /*        If want it True and currently False        */
  10408. IF (@WOptionValue = 'false' and (@Status & @WOptionNum)<> 0) or
  10409.     (@WOptionValue = 'true' and (@Status & @WOptionNum) = 0)
  10410. begin
  10411.  
  10412.     IF (  (@ObjType = 'P ' AND @WOptionStatus & @BitOptTypeP = 0) -- spt_values.status
  10413.     OR (@ObjType = 'X ' AND @WOptionStatus & @BitOptTypeX = 0))
  10414.     begin
  10415.         raiserror(15400,-1,61 ,@ObjType ,@WOptionName ,@ProcName)
  10416.         return @@error
  10417.     end
  10418.     
  10419.     select @CountUpdRows2 = @CountUpdRows2 + 1
  10420.  
  10421.     BEGIN TRANSACTION txn_11a_sp_procoption
  10422.  
  10423.     DBCC LockObjectSchema(@ProcName)
  10424.  
  10425.     IF (@WOptionName in (@StartUpString))
  10426.       begin
  10427.  
  10428.         IF (@WOptionValue = 'true')
  10429.         BEGIN
  10430.  
  10431.             UPDATE    master.dbo.sysobjects
  10432.             set    status = status |    @WOptionNum
  10433.             where  id = @ObjId
  10434.  
  10435.             -- set on config option 'scan for startup procs'
  10436.             if @cAutoProc = 0
  10437.             BEGIN
  10438.                 update master.dbo.sysconfigures
  10439.                 set value = 1
  10440.                 where config = 1547
  10441.             END
  10442.  
  10443.         END
  10444.         ELSE
  10445.         BEGIN
  10446.  
  10447.             UPDATE    master.dbo.sysobjects
  10448.             set    status = status & (~ @WOptionNum)
  10449.             where  id = @ObjId
  10450.  
  10451.             -- set off config option 'scan for startup procs'
  10452.             if @cAutoProc < 2
  10453.             BEGIN
  10454.                 update master.dbo.sysconfigures
  10455.                 set value = 0
  10456.                 where config = 1547
  10457.             END
  10458.         END
  10459.  
  10460.         IF (@@error <> 0)
  10461.         begin
  10462.             ROLLBACK TRANSACTION txn_11a_sp_procoption
  10463.         end
  10464.     end
  10465.  
  10466.     IF (@@trancount > @_trancount)
  10467.     begin
  10468.         COMMIT TRANSACTION txn_11a_sp_procoption
  10469.         reconfigure with override
  10470.     end
  10471. end
  10472.  
  10473. Raiserror(15391,-1,68 ,1 ,@WOptionName ,@OptionValue ,@CountUpdRows2)
  10474.  
  10475. Return (0)    --sp_procoption
  10476. go
  10477. Set ansi_nulls off
  10478. go
  10479. /*ANSI_NULLS off for after creation of sp_procoption*/
  10480.  
  10481.  
  10482. checkpoint
  10483. go
  10484.  
  10485.  
  10486. raiserror(15339,-1,-1,'sp_helpstartup')
  10487. go
  10488. create procedure sp_helpstartup --- 1996/09/20 13:56
  10489.      @procname    nvarchar(776)    = NULL
  10490. as
  10491. /***
  10492. This sproc is obsolete and undocu/nonexistent in MSSQL 7.0.
  10493. So use sp_procoption instead.
  10494. ***/
  10495.  
  10496. set nocount on
  10497. declare @retcode integer
  10498.  
  10499. execute @retcode = sp_procoption @procname,'startup'
  10500.  
  10501. return @retcode -- sp_helpstartup
  10502. go
  10503.  
  10504.  
  10505.  
  10506. raiserror(15339,-1,-1,'sp_unmakestartup')
  10507. go
  10508. create procedure sp_unmakestartup --- 1996/08/27 14:59
  10509. @procname nvarchar(776) = null
  10510. as
  10511. /***
  10512. This sproc is obsolete after 6.5; use sp_procoption!
  10513. ***/
  10514.  
  10515. set nocount on
  10516. declare @retcode integer
  10517.  
  10518. execute @retcode = sp_procoption @procname ,'startup' ,'false'
  10519.  
  10520. return @retcode -- sp_unmakestartup
  10521. go
  10522.  
  10523.  
  10524.  
  10525. raiserror(15339,-1,-1,'sp_makestartup')
  10526. go
  10527. create procedure sp_makestartup
  10528.     @procname nvarchar(776) = null
  10529. as
  10530. /***
  10531. This sproc is obsolete in MSSQL 7.0; use sp_procoption!
  10532. ***/
  10533.  
  10534. set nocount on
  10535. declare @retcode integer
  10536.  
  10537. execute @retcode = sp_procoption @procname ,'startup' ,'true'
  10538.  
  10539. return @retcode -- sp_makestartup
  10540. go
  10541.  
  10542.  
  10543.  
  10544. raiserror(15339,-1,-1,'sp_renamedb')
  10545. go
  10546. create procedure sp_renamedb --- 1996/08/20 13:52
  10547. @dbname sysname,            /* old (current) db name */
  10548. @newname sysname            /* new name we want to call it */
  10549. as
  10550. -- Use sp_rename instead.
  10551. declare @objid int            /* object id of the thing to rename */
  10552. declare @bitdesc varchar(30)        /* bit description for the db */
  10553. declare @curdbid int            /* id of database to be changed */
  10554.  
  10555. /*
  10556. **  If we're in a transaction, disallow this since it might make recovery
  10557. **  impossible.
  10558. */
  10559. set implicit_transactions off
  10560. if @@trancount > 0
  10561.     begin
  10562.         raiserror(15002,-1,-1,'sp_renamedb')
  10563.         return (1)
  10564.     end
  10565.  
  10566. /*
  10567. **  Only the SA can do this.
  10568. */
  10569. if not (is_srvrolemember('dbcreator') = 1)
  10570.     begin
  10571.         raiserror(15226,-1,-1)
  10572.         return (1)
  10573.     end
  10574.  
  10575. /*
  10576. **  Make sure the database exists.
  10577. */
  10578. if not exists (select * from master.dbo.sysdatabases where name = @dbname)
  10579.     begin
  10580.         raiserror(15010,-1,-1,@dbname)
  10581.         return (1)
  10582.     end
  10583.  
  10584. /*
  10585. **  Make sure that the @newname db doesn't already exist.
  10586. */
  10587. if exists (select * from master.dbo.sysdatabases where name = @newname)
  10588.     begin
  10589.         raiserror(15032,-1,-1,@newname)
  10590.         return (1)
  10591.     end
  10592.  
  10593. /*
  10594. **  Check to see that the @newname is valid.
  10595. */
  10596. declare @returncode int
  10597. exec @returncode = sp_validname @newname
  10598. if @returncode <> 0
  10599. begin
  10600.     raiserror(15224,-1,15,@newname)
  10601.     return(1)
  10602. end
  10603.  
  10604. /*
  10605. **  Don't allow the names of master, tempdb, and model to be changed.
  10606. */
  10607. if @dbname in ('master', 'model', 'tempdb')
  10608.     begin
  10609.         raiserror(15227,-1,-1,@dbname)
  10610.         return (1)
  10611.     end
  10612.  
  10613. /* Get current database id */
  10614. select @curdbid = db_id(@dbname)
  10615.  
  10616. /*
  10617. ** Check single user bit (4096)
  10618. ** Database must be in single user mode to necessitate the rid update in the
  10619. ** database's DBTABLE
  10620. */
  10621. select @bitdesc = null
  10622. select @bitdesc = v.name
  10623.     from master.dbo.spt_values v, master.dbo.sysdatabases d
  10624.     where d.dbid = @curdbid
  10625.         and v.type = 'D'
  10626.         and d.status & v.number = 4096
  10627.  
  10628. if @bitdesc is null
  10629.     begin
  10630.         raiserror(15228,-1,-1,@dbname)
  10631.         return(1)
  10632.     end
  10633.  
  10634. /*
  10635. **  Everything is ok so do it.
  10636. */
  10637. update master.dbo.sysdatabases set name = @newname, crdate = getdate()
  10638.     where name = @dbname
  10639.  
  10640. /*
  10641. ** Mark dbtable status dirty to update to the new name in Resources.
  10642. **
  10643. */
  10644. dbcc dbrepair (@newname,markdirty)
  10645.  
  10646.  
  10647. raiserror(15475,-1,-1)
  10648. raiserror(15476,-1,-1)
  10649.  
  10650. return (0) -- sp_renamedb
  10651. go
  10652.  
  10653. raiserror(15339,-1,-1,'sp_remove_tempdb_file')
  10654. go
  10655. create procedure sp_remove_tempdb_file @filename sysname
  10656. as
  10657. declare @fileid smallint
  10658. set nocount on
  10659.  
  10660. select @fileid = fileid 
  10661.     from sysaltfiles
  10662.     where dbid = 2  -- limit to tempdb files
  10663.     and name = @filename
  10664. if @fileid is null
  10665. begin
  10666.     -- file name does not exist 
  10667.     raiserror(15311,-1,-1,@filename)
  10668.     return (1)
  10669. end
  10670. if @fileid < 3
  10671. begin
  10672.     -- file is one of the primary files
  10673.     raiserror(15312,-1,-1,@filename)
  10674.     return (1)
  10675. end
  10676.  
  10677. delete sysaltfiles where dbid = 2 and fileid = @fileid
  10678. if @@error>0
  10679.    begin
  10680.       raiserror(15321,-1,-1, @filename)
  10681.       return (1)
  10682.    end
  10683. else
  10684.    begin
  10685.       raiserror(15322,-1,-1, @filename)
  10686.       return (0)
  10687.    end
  10688.     
  10689. go
  10690.  
  10691.  
  10692. raiserror(15339,-1,-1,'sp_rename')
  10693. go
  10694. /*ANSI_NULLS on for  creation of sp_rename*/
  10695. Set ansi_nulls on
  10696. go
  10697. CREATE PROCEDURE sp_rename
  10698.     @objname    nvarchar(776),        -- up to 3-part "old" name
  10699.     @newname    sysname,            -- one-part new name
  10700.     @objtype    varchar(13) = null    -- identifying the name
  10701. as
  10702. /********1*********2*********3*********4*********5**
  10703. DOCUMENTATION:
  10704.    [1]  To rename a table, the @objname (meaning OldName) parm can be
  10705. passed in totally unqualified or fully qualified.
  10706.    [2]  The SA or DBO can rename objects owned by lesser users,
  10707. without the need for SetUser.
  10708.    [3]  The Owner portion of a qualified name can usually be
  10709. passed in in the omitted form (as in MyDb..MyTab or MyTab).  The
  10710. typical exception is when the SA/DBO is trying to rename a table
  10711. where the @objname is present twice in sysobjects as a table
  10712. owned only by two different lesser users; requiring an explicit
  10713. owner qualifier in @objname.
  10714.    [4]  An unspecified Owner qualifier will default to the
  10715. current user if doing so will either resolve what would
  10716. otherwise be an ambiguity within @objtype, or will result
  10717. in exactly one match.
  10718.    [5]  If Database is part of the qualified @objname,
  10719. then it must match the current database.  The @newname parm can
  10720. never be qualified.
  10721.    [6]  Here are the valid @objtype values.  They correspond to
  10722. system tables which track each type:
  10723.       'column'  'database'  'index'  'object'  'userdatatype'
  10724. The @objtype parm is sometimes required.  It is always required
  10725. for databases.  It is required whenever ambiguities would
  10726. otherwise exist.  Explicit use of @objtype is always encouraged.
  10727.    [7]  Parms can use quoted_identifiers.  For example:
  10728.    Execute sp_rename 'amy."his table"','"her table"','object'
  10729. *********1*********2*********3*********4*********5*/
  10730. Set nocount      on
  10731. Set ansi_padding on
  10732.  
  10733. Declare @objtypeIN        varchar(13),
  10734.         @ExecRC            integer,
  10735.         @CurrentDb        sysname,
  10736.         @CountNumNodes    integer,
  10737.         @UnqualOldName    sysname,
  10738.         @QualName1        sysname,
  10739.         @QualName2        sysname,
  10740.         @QualName3        sysname,
  10741.         @OwnAndObjName    nvarchar(517),    -- "[owner].[object]"
  10742.         @objid            integer,
  10743.         @xtype            char(2),
  10744.         @indid            smallint,
  10745.         @colid            smallint,
  10746.         @cnstid            integer,
  10747.         @parent_obj        integer,
  10748.         @xusertype        smallint,
  10749.         @ownerid        smallint,
  10750.         @objid_tmp        integer,
  10751.         @xtype_tmp        char(2),
  10752.         @retcode        int,
  10753.         @replinfo        int,
  10754.         @replbits        int
  10755. -- initial (non-null) settings
  10756. Select    @CurrentDb        = db_name(),
  10757.         @objtypeIN        = @objtype,
  10758.         @replbits        = 129    --Indicates table is used in replication
  10759.  
  10760. -- make type case insensitive
  10761. select @objtype = lower(@objtypeIN)
  10762.  
  10763. ------------------------------------------------------------------------
  10764. -------------------  PHASE 10:  Simple parm edits  ---------------------
  10765. ------------------------------------------------------------------------
  10766.  
  10767. -- Valid rename-type param?
  10768. IF (@objtype is not null AND
  10769.     @objtype not in ('column', 'database', 'index', 'object', 'userdatatype'))
  10770. begin
  10771.     raiserror(15249,-1,-1,@objtypeIN,0)
  10772.     return 1
  10773. end
  10774. -- null names?
  10775. IF (@newname IS null)
  10776. begin
  10777.     raiserror(15223,-1,11,'NewName')
  10778.     return 1
  10779. end
  10780. if (@objname IS null)
  10781. begin
  10782.     raiserror(15223,-1,-1,'OldName')
  10783.     return 1
  10784. end
  10785.  
  10786. ---------------  Is NewName minimally valid?
  10787.  
  10788. --Check for valid rename name
  10789. exec @retcode = sp_validname @newname
  10790. if @retcode <> 0
  10791. begin
  10792.     raiserror(15224,-1,15,@newname)
  10793.     return 1
  10794. end
  10795.  
  10796. -------- Parse apart the perhaps dots-qualified old name.
  10797.  
  10798. select @UnqualOldName = parsename(@objname, 1),
  10799.         @QualName1 = parsename(@objname, 2),
  10800.         @QualName2 = parsename(@objname, 3),
  10801.         @QualName3 = parsename(@objname, 4)
  10802. IF (@UnqualOldName IS Null)
  10803. begin
  10804.     raiserror(15253,-1,-1,@objname)
  10805.     return 1
  10806. end
  10807.  
  10808. -- count name parts --
  10809. select @CountNumNodes = CASE WHEN @QualName3 IS NOT NULL THEN 4
  10810.                              WHEN @QualName2 IS NOT NULL THEN 3
  10811.                              WHEN @QualName1 IS NOT NULL THEN 2
  10812.                              ELSE 1 END
  10813. IF (@objtype  = 'database' AND @CountNumNodes > 1)
  10814. begin
  10815.     Raiserror(15395,-1,20,@objtypeIN)
  10816.     return 1
  10817. end
  10818. if (@objtype in ('object','userdatatype') AND @CountNumNodes > 3)
  10819. begin
  10820.     raiserror(15225,-1,-1,@objname, @CurrentDb, @objtypeIN)
  10821.     return 1
  10822. end
  10823.  
  10824.  
  10825. ---------------------------------------------------------------------------
  10826. ----------------------  PHASE 20:  Settle Parm1ItemType  ------------------
  10827. ---------------------------------------------------------------------------
  10828.  
  10829. ------------- database?
  10830. IF (@objtype  = 'database')
  10831. begin
  10832.     execute @ExecRC = sp_renamedb @UnqualOldName ,@newname -- de-docu old sproc
  10833.     IF @ExecRC <> 0
  10834.         return 1
  10835.     GOTO LABEL_51_AFTERUPDATES
  10836. end
  10837.  
  10838. -- assuming column/index-name, obtain object/column id's
  10839. if @QualName2 is not null
  10840.     select @objid = object_id(QuoteName(@QualName2) +'.'+ QuoteName(@QualName1))
  10841. else
  10842.     select @objid = object_id(QuoteName(@QualName1))
  10843.  
  10844. select @xtype = xtype, @replinfo = replinfo from sysobjects where id = @objid
  10845.  
  10846. ------------ column?
  10847. if (@objtype = 'column' or @objtypeIN is null)
  10848. begin
  10849.     -- find column
  10850.     select @colid = NULL
  10851.     if (@xtype in ('U','V'))
  10852.         select @colid = colid from syscolumns
  10853.                 where id = @objid and name = @UnqualOldName
  10854.  
  10855.     -- check for wrong param
  10856.     if ((@colid is not null AND @objtype <> 'column') OR
  10857.         (@colid is null AND @objtype = 'column'))
  10858.     begin
  10859.         raiserror(15248,-1,-1,@objtypeIN)
  10860.         return 1
  10861.     end
  10862.  
  10863.     -- remember if we've found a column
  10864.     IF (@colid is not null)
  10865.     begin
  10866.         if (@replinfo & @replbits <> 0)
  10867.             begin
  10868.                 raiserror(15051,-1,-1)
  10869.                 return (0)
  10870.             end
  10871.         select @objtype = 'column'
  10872.     end
  10873. end
  10874.  
  10875. ------------ index?
  10876. if (lower(@objtype) = 'index' or @objtypeIN is null)
  10877. begin
  10878.     -- find index
  10879.     if (@xtype in ('U'))
  10880.         select @indid = indid from sysindexes
  10881.                 where id = @objid and name = @UnqualOldName
  10882.                     AND indid NOT IN (0, 255)
  10883.  
  10884.     -- check for wrong param
  10885.     if ((@indid is not null AND @objtype <> 'index') OR
  10886.         (@indid is null AND @objtype = 'index'))
  10887.     begin
  10888.         raiserror(15248,-1,-1,@objtypeIN)
  10889.         return 1
  10890.     end
  10891.  
  10892.     if (@indid is not null)
  10893.     begin
  10894.         select @objtype = 'index'
  10895.         select @cnstid = id, @xtype = xtype from sysobjects
  10896.             where name = @UnqualOldName AND parent_obj = @objid and xtype in ('PK','UQ')
  10897.     end
  10898. end
  10899.  
  10900.  
  10901. ------------ object?
  10902. if (@objtype = 'object' or @objtypeIN is null)
  10903. begin
  10904.     -- get object id, type
  10905.     select @objid_tmp = object_id(@objname)
  10906.  
  10907.     select @xtype_tmp = xtype, @replinfo = replinfo 
  10908.     from sysobjects where id = @objid_tmp
  10909.  
  10910.     if @xtype_tmp = 'S'        -- UNDONE: skip others?
  10911.         select @objid_tmp = NULL
  10912.  
  10913.     -- check for wrong param
  10914.     if ((@objid_tmp is not null AND @objtype <> 'object') OR
  10915.         (@objid_tmp is null AND @objtype = 'object'))
  10916.     begin
  10917.         raiserror(15248,-1,-1,@objtypeIN)
  10918.         return 1
  10919.     end
  10920.  
  10921.     if (@objid_tmp is not null)
  10922.     begin
  10923.  
  10924.         if (@xtype_tmp in ('U'))
  10925.         begin
  10926.             if (@replinfo & @replbits <> 0)
  10927.             begin
  10928.                 raiserror(15051,-1,-1)
  10929.                 return (0)
  10930.             end
  10931.         end
  10932.  
  10933.         select @objtype = 'object', @objid = @objid_tmp, @xtype = @xtype_tmp
  10934.  
  10935.         if (@xtype in ('PK','UQ'))
  10936.             select @parent_obj = parent_obj from sysobjects where id = @objid
  10937.     end
  10938. end
  10939.  
  10940.  
  10941. ------------ type?
  10942. if (@objtype = 'userdatatype' or @objtypeIN is null)
  10943. begin
  10944.     select @xusertype = xusertype from systypes
  10945.         where name = @UnqualOldName and xusertype > 256
  10946.             AND (@QualName1 is null or uid = user_id(@QualName1))
  10947.  
  10948.     -- check for wrong param
  10949.     if ((@xusertype is not null AND @objtype <> 'userdatatype') OR
  10950.         (@xusertype is null AND @objtype = 'userdatatype'))
  10951.     begin
  10952.         raiserror(15248,-1,-1,@objtypeIN)
  10953.         return 1
  10954.     end
  10955.  
  10956.     if (@xusertype IS NOT null)
  10957.         select @objtype = 'userdatatype'
  10958. end
  10959.  
  10960. ---------------------------------------------------------------------
  10961. -------------------  PHASE 30:  More parm edits  --------------------
  10962. ---------------------------------------------------------------------
  10963.  
  10964. -- item type determined?
  10965. if (@objtype IS null)
  10966. begin
  10967.     raiserror(15225,-1,-1,@objname, @CurrentDb, @objtypeIN)
  10968.     return 1
  10969. end
  10970.  
  10971. -- was the original name valid given this type?
  10972. if (@objtype in ('object','userdatatype') AND @CountNumNodes > 3)
  10973. begin
  10974.     raiserror(15225,-1,-1,@objname, @CurrentDb, @objtypeIN)
  10975.     return 1
  10976. end
  10977.  
  10978. -- verify db qualifier is current db
  10979. if (@objtype in ('object','userdatatype'))
  10980.     select @QualName3 = @QualName2
  10981. if (isnull(@QualName3, @CurrentDb) <> @CurrentDb)
  10982. begin
  10983.     raiserror(15333,-1,-1,@QualName3)
  10984.     return 1
  10985. end
  10986.  
  10987. -- get owner id and check permissions
  10988. if (@objtype = 'userdatatype')
  10989.     select @ownerid = uid from systypes where xusertype = @xusertype
  10990. else
  10991.     select @ownerid = ObjectProperty(@objid, 'ownerid')
  10992. if (    (not (1 = is_member('db_owner')))
  10993.     AND (not (1 = is_member('db_ddladmin')))
  10994.     AND (not (1 = is_member(user_name(@ownerid)))) )
  10995. begin
  10996.     raiserror(15334,-1,-1)
  10997.     return 1
  10998. end
  10999.  
  11000. -- make sure orig no longer shows null
  11001. if @objtypeIN is null
  11002.     select @objtypeIN = @objtype
  11003.  
  11004. -- Check for name clashing with existing name(s)
  11005. if (@newname <> @UnqualOldName)
  11006. begin
  11007.     -- column name clash?
  11008.     if (@objtype = 'column')
  11009.         if (ColumnProperty(@objid, @newname, 'isidentity') is not null)
  11010.             select @UnqualOldName = NULL
  11011.     -- object name clash?
  11012.     if ( (@objtype = 'object' AND @xtype in ('PK','UQ'))
  11013.             OR @objtype = 'index')
  11014.         if exists (select * from sysindexes where id = @objid and name = @newname
  11015.                     and indid not in (0,255))
  11016.             select @UnqualOldName = NULL
  11017.     -- index name clash?
  11018.     if (@objtype = 'object' OR @cnstid IS NOT null)
  11019.         if (object_id(QuoteName(user_name(@ownerid)) +'.'+ QuoteName(@newname)) is not null)
  11020.             select @UnqualOldName = NULL
  11021.     -- type name clash?
  11022.     if (@objtype = 'userdatatype')
  11023.         if exists (select * from systypes where name = @newname)
  11024.             select @UnqualOldName = NULL
  11025.     -- stop on clash
  11026.     if (@UnqualOldName is null)
  11027.     begin
  11028.         raiserror(15335,-1,-1,@newname,@objtypeIN)
  11029.         return 1
  11030.     end
  11031. end
  11032.  
  11033.  
  11034. --------------------------------------------------------------------------
  11035. --------------------  PHASE 34:  Cautionary messages  --------------------
  11036. --------------------------------------------------------------------------
  11037.  
  11038. -- WITH DEFERRED RESOLUTION, SYSDEPENDS IS NOT VERY ACCURATE, SO WE ALSO
  11039. --    RAISE THIS WARNING **UNCONDITIONALLY**, EVEN FOR NON-OBJECT RENAMES
  11040. raiserror(15477,-1,-1)
  11041.  
  11042. -- warn about dependencies...
  11043. if (@objtype = 'objects')
  11044.     if exists (select * from sysdepends where depid = @objid)
  11045.         raiserror(15337,-1,-1)
  11046.  
  11047.  
  11048. --------------------------------------------------------------------------
  11049. ---------------------  PHASE 40:  Update system tables  ------------------
  11050. --------------------------------------------------------------------------
  11051.  
  11052. -- obtain owner-qual object name (for most below)
  11053. select @OwnAndObjName = QuoteName(user_name(@ownerid))+'.'+QuoteName(object_name(@objid))
  11054.  
  11055. -- DO THE UPDATES --
  11056. if (@objtype = 'userdatatype')                        -------- change type name
  11057.     UPDATE systypes set name = @newname where xusertype = @xusertype
  11058. else if (@objtype = 'object')                        -------- change object name
  11059. begin
  11060.     BEGIN  TRANSACTION
  11061.     -- Locks Object and increments schema_ver
  11062.     DBCC LockObjectSchema(@OwnAndObjName)
  11063.     -- update the object name
  11064.     UPDATE sysobjects set name = @newname where id = @objid
  11065.     -- update index-cnst name (no rows changed if not 'PK' or 'UQ')
  11066.     if (@xtype in ('PK','UQ'))
  11067.         UPDATE sysindexes set name = @newname where id = @parent_obj and name = @UnqualOldName
  11068.     -- update base/text index name (no rows changed if not there)
  11069.     else if (@xtype = 'U')
  11070.     begin
  11071.         UPDATE sysindexes set name = @newname where id = @objid AND indid = 0
  11072.         UPDATE sysindexes set name = convert(sysname,'t'+@newname)
  11073.                             where id = @objid AND indid = 255
  11074.     end
  11075.     COMMIT TRANSACTION
  11076. end
  11077. else if (@objtype = 'index')                        -------- change index name
  11078. begin
  11079.     BEGIN  TRANSACTION
  11080.     -- Locks Object and increments schema_ver.
  11081.     DBCC LockObjectSchema(@OwnAndObjName)
  11082.     -- update the index name
  11083.     UPDATE sysindexes set name = @newname where id = @objid and indid = @indid
  11084.     -- change object name if cnst
  11085.     if (@cnstid IS NOT null)
  11086.         UPDATE sysobjects set name = @newname where id = @cnstid
  11087.     COMMIT TRANSACTION
  11088. end
  11089. else if (@objtype = 'column')                        -------- change column name
  11090. begin
  11091.     -- Use DBCC to check for column in use by check-constraint, computed-column, etc
  11092.     -- THIS IS NOT A DOCUMENTED DBCC: DO NOT USE DIRECTLY!
  11093.     DBCC RENAMECOLUMN ( @OwnAndObjName, @UnqualOldName, @newname )
  11094. end
  11095.  
  11096.  
  11097. -------------------------  Finalization  -----------------------
  11098. LABEL_51_AFTERUPDATES:
  11099. Raiserror(15338,-1,-1,@objtypeIN,@newname)
  11100. return 0 -- sp_rename
  11101. go
  11102. /*ANSI_NULLS off for after creation of sp_rename*/
  11103. Set ansi_nulls off
  11104. go
  11105.  
  11106.  
  11107.  
  11108. checkpoint
  11109. go
  11110.  
  11111. raiserror(15339,-1,-1,'sp_resetstatus')
  11112. Go
  11113.  
  11114. CREATE PROCEDURE sp_resetstatus  -- 1995/11/30 14:12 #12092
  11115.        @DBName          sysname
  11116. as
  11117.  
  11118. Set nocount on
  11119.  
  11120. Declare
  11121.        @msg             nvarchar(280)
  11122.       ,@RetCode         integer
  11123.       ,@_error          integer
  11124.       ,@_rowcount       integer
  11125.       ,@int1            integer
  11126.       ,@bitSuspect      integer
  11127.       ,@mode            integer
  11128.       ,@status          integer
  11129.  
  11130. Select
  11131.        @RetCode         = 0  -- 0=no_problem, 1=some_problem
  11132.  
  11133. ---------------------  Restrict to SA  -------------------------
  11134.  
  11135. IF suser_id() <> 1
  11136.    begin
  11137.    RaisError(15003,-1,-1,'sysadmin')
  11138.    Select @RetCode = 1
  11139.    GOTO LABEL_86BYEBYE
  11140.    end
  11141.  
  11142.  
  11143. ------------------  Get SuspectBit id value  ------------------
  11144.  
  11145. SELECT       @bitSuspect = min(number)
  11146.       from
  11147.              master..spt_values
  11148.       where  type = 'D  '
  11149.       and    name = 'not recovered'  -- 256, Suspect
  11150.  
  11151. ----------------------  Forbid active txn  ---------------------
  11152.  
  11153. --- (Prior spt_values Sel trips SET implicit_transactions!)
  11154.  
  11155.  
  11156. IF @@trancount > 0
  11157.    begin
  11158.    RaisError(15002,-1,-1,'sp_resetstatus')
  11159.    Select @RetCode = 1
  11160.    GOTO LABEL_86BYEBYE
  11161.    end
  11162.  
  11163.  
  11164. ---------------  Obtain/Report pre-Update values  --------------------
  11165.  
  11166. SELECT
  11167.              @mode   = min(mode)
  11168.             ,@status = min(status)
  11169.       from
  11170.              master..sysdatabases
  11171.       where  name = @DBName
  11172.  
  11173. IF @@error <> 0 OR @status IS Null
  11174.    begin
  11175.    RaisError(15010,-1,-1,@DBName)
  11176.    Select @RetCode = 1
  11177.    GOTO LABEL_86BYEBYE
  11178.    end
  11179.  
  11180.  
  11181. Select @int1 = @status & @bitSuspect
  11182.  
  11183.  
  11184. Raiserror(15052,-1,-1 ,@DBName ,@mode ,@status ,@int1)
  11185.  
  11186. ---------------------  Update sysdatabases row  ---------------------
  11187.  
  11188. BEGIN TRANSACTION
  11189.  
  11190.  
  11191. UPDATE
  11192.              master..sysdatabases
  11193.       set
  11194.              mode    = 0
  11195.             ,status  = status & (~ @bitSuspect)
  11196.       where  name    = @DBName
  11197.       and
  11198.             (mode   <> 0      OR
  11199.              status  & @bitSuspect > 0
  11200.             )
  11201.  
  11202. Select @_error = @@error ,@_rowcount = @@rowcount
  11203.  
  11204.  
  11205. IF @_error <> 0
  11206.    begin
  11207.  
  11208.    ROLLBACK TRANSACTION
  11209.  
  11210.    RaisError(15055,-1,-1)
  11211.    Select @RetCode = 1
  11212.    GOTO LABEL_86BYEBYE
  11213.    end
  11214.  
  11215.  
  11216. COMMIT TRANSACTION
  11217.  
  11218. -------- Report the results
  11219.  
  11220. IF @_rowcount = 0
  11221.    begin
  11222.    Raiserror(15056,-1,-1)
  11223.    end
  11224.  
  11225. ELSE
  11226.    begin
  11227.  
  11228.    Raiserror(15073,-1,-1, @DBName,@bitSuspect)
  11229.  
  11230.    Raiserror(15074,-1,-1)
  11231.  
  11232.    end
  11233.  
  11234.  
  11235. LABEL_86BYEBYE:
  11236.  
  11237. RETURN @RetCode
  11238.  
  11239. Go
  11240.  
  11241.  
  11242. raiserror(15339,-1,-1,'sp_add_file_recover_suspect_db')
  11243. Go
  11244. --
  11245. -- Name: sp_add_file_recover_suspect_db
  11246. -- Purpose: Adds a data or log file to a suspect database and runs
  11247. --         recovery on the database.  This SP should only be used
  11248. --        on databases that have been marked suspect due to
  11249. --        insufficient data (error 1105) or log (error 9002) space.
  11250. -- Note: This SP is not documented.  Only sp_add_data_file_recover_suspect_db
  11251. --    and sp_add_log_file_recover_suspect_db below are documented
  11252. --
  11253. create procedure sp_add_file_recover_suspect_db
  11254.     @dbName     sysname            -- database name
  11255.     ,@fileType    nvarchar(4)        -- "data" or "log"
  11256.     ,@filegroup    nvarchar(260)        -- file group for new file
  11257.     ,@name        nvarchar(260)        -- logical file name
  11258.     ,@filename    nvarchar(260)        -- OS file name
  11259.     ,@size        nvarchar(20)     = NULL    -- initial file size
  11260.     ,@maxsize    nvarchar(20)     = NULL    -- maximum file size
  11261.     ,@filegrowth    nvarchar(20)     = NULL    -- growth increment
  11262.     
  11263. as
  11264.  
  11265. declare @currentStatus int
  11266. declare @suspectBit int
  11267. declare @dboOnlyBit int
  11268. declare @emergencyModeBit int
  11269. declare @returnCode int
  11270. declare @addCmd nvarchar(4000)
  11271. declare @isLog    int
  11272.  
  11273. set nocount on
  11274. select @suspectBit = 0x100
  11275. select @currentStatus = 0
  11276. select @returnCode = 0
  11277.  
  11278. ---------------------  Restrict to SA  -------------------------
  11279.  
  11280. IF suser_id() <> 1
  11281. begin
  11282.    RaisError(15003,-1,-1,'sysadmin')
  11283.    Select @returnCode = 1
  11284.    GOTO LABEL_FAILURE
  11285. end
  11286.  
  11287.  
  11288. ------------------  Get Status Bit id values  ------------------
  11289.  
  11290. SELECT       @suspectBit = min(number)
  11291.       from
  11292.              master..spt_values
  11293.       where  type = 'D  '
  11294.       and    name = 'not recovered'  -- 256, Suspect
  11295.  
  11296. SELECT       @dboOnlyBit = min(number)
  11297.       from
  11298.              master..spt_values
  11299.       where  type = 'D  '
  11300.       and    name = 'dbo use only'  -- 2048, dbo only
  11301.  
  11302. SELECT       @emergencyModeBit = min(number)
  11303.       from
  11304.              master..spt_values
  11305.       where  type = 'D  '
  11306.       and    name = 'emergency mode'  -- 32768, dbo only
  11307.  
  11308. --print 'Bit values ' + convert(char(10), @suspectBit) + convert(char(10), @dboOnlyBit) + convert(char(10), @emergencyModeBit)
  11309.  
  11310. -- Determine if this is a data or log file
  11311. --
  11312. IF (UPPER (@fileType) = 'DATA')
  11313. begin
  11314.     select @isLog = 0
  11315. end
  11316. ELSE IF (UPPER (@fileType) = 'LOG')
  11317. begin
  11318.     select @isLog = 1
  11319. end
  11320. ELSE
  11321. begin
  11322.     print 'Must specify data or log file type'
  11323.     select @returnCode = 1
  11324.     GOTO LABEL_FAILURE
  11325. end
  11326.  
  11327.  
  11328.  
  11329. IF @@trancount > 0
  11330. begin
  11331.    RaisError(15002,-1,-1,'sp_add_file_recover_suspect_db')
  11332.    Select @returnCode = 1
  11333.    GOTO LABEL_FAILURE
  11334. end
  11335.  
  11336. -- check that current status includes suspect or emergency-mode
  11337. -- otherwise fail with database does not exist
  11338. --
  11339. select @currentStatus = status from sysdatabases where name = @dbName
  11340. if (((@currentStatus & @suspectBit) = 0) AND 
  11341.     ((@currentStatus & @emergencyModeBit) = 0))
  11342. begin
  11343.     RaisError(15010,-1,-1,@dbName)
  11344.     select @returnCode = 1
  11345.     goto LABEL_FAILURE
  11346. end
  11347.  
  11348. -- set new temporary status to dbo-only and emergency-mode
  11349. --
  11350. BEGIN TRAN
  11351. update sysdatabases set status = (status | @dboOnlyBit | @emergencyModeBit) where name = @dbName
  11352. IF @@error <> 0
  11353. begin
  11354.    ROLLBACK TRANSACTION
  11355.    RaisError(15055,-1,-1)
  11356.    Select @returnCode = 1
  11357.    GOTO LABEL_FAILURE
  11358. end
  11359. COMMIT TRAN
  11360. checkpoint
  11361.  
  11362. -- Build the Alter Database Add File string
  11363. --
  11364. select @addCmd = 'ALTER DATABASE ' + @dbName + ' ADD'
  11365. IF (@isLog = 1)
  11366. begin
  11367.     select @addCmd = @addCmd + ' LOG FILE'
  11368. end
  11369. ELSE
  11370. begin
  11371.     select @addCmd = @addCmd + ' FILE'
  11372. end
  11373. select @addCmd = @addCmd + '(NAME = [' + @name + '], FILENAME = ''' + @filename + ''''
  11374. if (@size IS NOT NULL)
  11375. begin
  11376.     select @addCmd = @addCmd + ', SIZE = ' + @size
  11377. end
  11378. if (@maxsize IS NOT NULL)
  11379. begin
  11380.     select @addCmd = @addCmd + ', MAXSIZE = ' + @maxsize
  11381. end
  11382. if (@filegrowth IS NOT NULL)
  11383. begin
  11384.     select @addCmd = @addCmd + ', FILEGROWTH = ' + @filegrowth
  11385. end
  11386. select @addCmd = @addCmd + ' )'
  11387. if (@filegroup IS NOT NULL)
  11388. begin
  11389.     select @addCmd = @addCmd + ' TO FILEGROUP [' + @filegroup + ']'
  11390. end
  11391. print @addCmd
  11392.  
  11393. EXECUTE (@addCmd)
  11394.  
  11395. -- restore status to what it was before adding the file
  11396. --
  11397. BEGIN TRAN
  11398. update sysdatabases set status = @currentStatus where name = @dbName
  11399. IF @@error <> 0
  11400.    begin
  11401.  
  11402.    ROLLBACK TRANSACTION
  11403.  
  11404.    RaisError(15055,-1,-1)
  11405.    Select @returnCode = 1
  11406.    GOTO LABEL_FAILURE
  11407.    end
  11408. COMMIT TRAN
  11409. checkpoint
  11410.  
  11411. -- Turn off suspect bit if it is on
  11412. --
  11413. if ((@currentStatus & @suspectBit) <> 0)
  11414. begin
  11415.     exec sp_resetstatus @dbName
  11416. end
  11417.  
  11418. -- Run recovery on the database
  11419. --
  11420. select @addCmd = 'dbcc dbrecover (' + @dbName + ')'
  11421. exec (@addCmd)
  11422.  
  11423.  
  11424. GOTO LABEL_SUCCESS
  11425.  
  11426. LABEL_FAILURE:
  11427.     --print 'Failed to add file to and recover the suspect database.'
  11428.     return @returnCode
  11429.  
  11430. LABEL_SUCCESS:
  11431.     --print 'Successfully added file to the database'
  11432.     return @returnCode
  11433. -- sp_add_file_recover_suspect_db
  11434. go
  11435.  
  11436.  
  11437. raiserror(15339,-1,-1,'sp_add_data_file_recover_suspect_db')
  11438. Go
  11439. --
  11440. -- Name: sp_add_data_file_recover_suspect_db
  11441. -- Purpose: Adds a data file to a suspect database and runs
  11442. --         recovery on the database.  This SP should only be used
  11443. --        on databases that have been marked suspect due to
  11444. --        insufficient data (error 1105) or log (error 9002) space.
  11445. --
  11446. create procedure sp_add_data_file_recover_suspect_db
  11447.     @dbName     sysname            -- database name
  11448.     ,@filegroup    nvarchar(260)        -- file group for new file
  11449.     ,@name        nvarchar(260)        -- logical file name
  11450.     ,@filename    nvarchar(260)        -- OS file name
  11451.     ,@size        nvarchar(20)     = NULL    -- initial file size
  11452.     ,@maxsize    nvarchar(20)     = NULL    -- maximum file size
  11453.     ,@filegrowth    nvarchar(20)     = NULL    -- growth increment
  11454. as
  11455. execute sp_add_file_recover_suspect_db @dbName, 'DATA', @filegroup, @name, @filename, @size, @maxsize, @filegrowth
  11456. go
  11457.  
  11458. raiserror(15339,-1,-1,'sp_add_log_file_recover_suspect_db')
  11459. Go
  11460. --
  11461. -- Name: sp_add_log_file_recover_suspect_db
  11462. -- Purpose: Adds a log file to a suspect database and runs
  11463. --         recovery on the database.  This SP should only be used
  11464. --        on databases that have been marked suspect due to
  11465. --        insufficient data (error 1105) or log (error 9002) space.
  11466. --
  11467. create procedure sp_add_log_file_recover_suspect_db
  11468.     @dbName     sysname            -- database name
  11469.     ,@name        nvarchar(260)        -- logical file name
  11470.     ,@filename    nvarchar(260)        -- OS file name
  11471.     ,@size        nvarchar(20)     = NULL    -- initial file size
  11472.     ,@maxsize    nvarchar(20)     = NULL    -- maximum file size
  11473.     ,@filegrowth    nvarchar(20)     = NULL    -- growth increment
  11474. as
  11475. execute sp_add_file_recover_suspect_db @dbName, 'LOG', NULL, @name, @filename, @size, @maxsize, @filegrowth
  11476. go
  11477.  
  11478.  
  11479. raiserror(15339,-1,-1,'sp_spaceused')
  11480. go
  11481. create procedure sp_spaceused --- 1996/08/20 17:01
  11482. @objname nvarchar(776) = null,        -- The object we want size on.
  11483. @updateusage varchar(5) = false        -- Param. for specifying that
  11484.                     -- usage info. should be updated.
  11485. as
  11486.  
  11487. declare @id    int            -- The object id of @objname.
  11488. declare @type    character(2) -- The object type.
  11489. declare    @pages    int            -- Working variable for size calc.
  11490. declare @dbname sysname
  11491. declare @dbsize dec(15,0)
  11492. declare @bytesperpage    dec(15,0)
  11493. declare @pagesperMB        dec(15,0)
  11494.  
  11495. /*Create temp tables before any DML to ensure dynamic
  11496. **  We need to create a temp table to do the calculation.
  11497. **  reserved: sum(reserved) where indid in (0, 1, 255)
  11498. **  data: sum(dpages) where indid < 2 + sum(used) where indid = 255 (text)
  11499. **  indexp: sum(used) where indid in (0, 1, 255) - data
  11500. **  unused: sum(reserved) - sum(used) where indid in (0, 1, 255)
  11501. */
  11502. create table #spt_space
  11503. (
  11504.     rows        int null,
  11505.     reserved    dec(15) null,
  11506.     data        dec(15) null,
  11507.     indexp        dec(15) null,
  11508.     unused        dec(15) null
  11509. )
  11510.  
  11511. /*
  11512. **  Check to see if user wants usages updated.
  11513. */
  11514.  
  11515. if @updateusage is not null
  11516.     begin
  11517.         select @updateusage=lower(@updateusage)
  11518.  
  11519.         if @updateusage not in ('true','false')
  11520.             begin
  11521.                 raiserror(15143,-1,-1,@updateusage)
  11522.                 return(1)
  11523.             end
  11524.     end
  11525. /*
  11526. **  Check to see that the objname is local.
  11527. */
  11528. if @objname IS NOT NULL
  11529. begin
  11530.  
  11531.     select @dbname = parsename(@objname, 3)
  11532.  
  11533.     if @dbname is not null and @dbname <> db_name()
  11534.         begin
  11535.             raiserror(15250,-1,-1)
  11536.             return (1)
  11537.         end
  11538.  
  11539.     if @dbname is null
  11540.         select @dbname = db_name()
  11541.  
  11542.     /*
  11543.     **  Try to find the object.
  11544.     */
  11545.     select @id = null
  11546.     select @id = id, @type = xtype
  11547.         from sysobjects
  11548.             where id = object_id(@objname)
  11549.  
  11550.     /*
  11551.     **  Does the object exist?
  11552.     */
  11553.     if @id is null
  11554.         begin
  11555.             raiserror(15009,-1,-1,@objname,@dbname)
  11556.             return (1)
  11557.         end
  11558.  
  11559.  
  11560.     if not exists (select * from sysindexes
  11561.                 where @id = id and indid < 2)
  11562.  
  11563.         if      @type in ('P ','D ','R ','TR','C ','RF') --data stored in sysprocedures
  11564.                 begin
  11565.                     raiserror(15234,-1,-1)
  11566.                     return (1)
  11567.                 end
  11568.         else if @type = 'V ' -- View => no physical data storage.
  11569.                 begin
  11570.                     raiserror(15235,-1,-1)
  11571.                     return (1)
  11572.                 end
  11573.         else if @type in ('PK','UQ') -- no physical data storage. --?!?! too many similar messages
  11574.                 begin
  11575.                     raiserror(15064,-1,-1)
  11576.                     return (1)
  11577.                 end
  11578.         else if @type = 'F ' -- FK => no physical data storage.
  11579.                 begin
  11580.                     raiserror(15275,-1,-1)
  11581.                     return (1)
  11582.                 end
  11583. end
  11584.  
  11585. /*
  11586. **  Update usages if user specified to do so.
  11587. */
  11588.  
  11589. if @updateusage = 'true'
  11590.     begin
  11591.         if @objname is null
  11592.             dbcc updateusage(0) with no_infomsgs
  11593.         else
  11594.             dbcc updateusage(0,@objname) with no_infomsgs
  11595.         print ' '
  11596.     end
  11597.  
  11598.  
  11599. set nocount on
  11600.  
  11601. /*
  11602. **  If @id is null, then we want summary data.
  11603. */
  11604. /*    Space used calculated in the following way
  11605. **    @dbsize = Pages used
  11606. **    @bytesperpage = d.low (where d = master.dbo.spt_values) is
  11607. **    the # of bytes per page when d.type = 'E' and
  11608. **    d.number = 1.
  11609. **    Size = @dbsize * d.low / (1048576 (OR 1 MB))
  11610. */
  11611. if @id is null
  11612. begin
  11613.     select @dbsize = sum(convert(dec(15),size))
  11614.         from dbo.sysfiles
  11615.  
  11616.     select @bytesperpage = low
  11617.         from master.dbo.spt_values
  11618.         where number = 1
  11619.             and type = 'E'
  11620.     select @pagesperMB = 1048576 / @bytesperpage
  11621.  
  11622.     select  database_name = db_name(),
  11623.         database_size =
  11624.             ltrim(str(@dbsize / @pagesperMB,15,2) + ' MB'),
  11625.         'unallocated space' =
  11626.             ltrim(str((@dbsize -
  11627.                 (select sum(convert(dec(15),reserved))
  11628.                     from sysindexes
  11629.                         where indid in (0, 1, 255)
  11630.                 )) / @pagesperMB,15,2)+ ' MB')
  11631.  
  11632.     print ' '
  11633.     /*
  11634.     **  Now calculate the summary data.
  11635.     **  reserved: sum(reserved) where indid in (0, 1, 255)
  11636.     */
  11637.     insert into #spt_space (reserved)
  11638.         select sum(convert(dec(15),reserved))
  11639.             from sysindexes
  11640.                 where indid in (0, 1, 255)
  11641.  
  11642.     /*
  11643.     ** data: sum(dpages) where indid < 2
  11644.     **    + sum(used) where indid = 255 (text)
  11645.     */
  11646.     select @pages = sum(convert(dec(15),dpages))
  11647.             from sysindexes
  11648.                 where indid < 2
  11649.     select @pages = @pages + isnull(sum(convert(dec(15),used)), 0)
  11650.         from sysindexes
  11651.             where indid = 255
  11652.     update #spt_space
  11653.         set data = @pages
  11654.  
  11655.  
  11656.     /* index: sum(used) where indid in (0, 1, 255) - data */
  11657.     update #spt_space
  11658.         set indexp = (select sum(convert(dec(15),used))
  11659.                 from sysindexes
  11660.                     where indid in (0, 1, 255))
  11661.                 - data
  11662.  
  11663.     /* unused: sum(reserved) - sum(used) where indid in (0, 1, 255) */
  11664.     update #spt_space
  11665.         set unused = reserved
  11666.                 - (select sum(convert(dec(15),used))
  11667.                     from sysindexes
  11668.                         where indid in (0, 1, 255))
  11669.  
  11670.     select reserved = ltrim(str(reserved * d.low / 1024.,15,0) +
  11671.                 ' ' + 'KB'),
  11672.         data = ltrim(str(data * d.low / 1024.,15,0) +
  11673.                 ' ' + 'KB'),
  11674.         index_size = ltrim(str(indexp * d.low / 1024.,15,0) +
  11675.                 ' ' + 'KB'),
  11676.         unused = ltrim(str(unused * d.low / 1024.,15,0) +
  11677.                 ' ' + 'KB')
  11678.         from #spt_space, master.dbo.spt_values d
  11679.         where d.number = 1
  11680.             and d.type = 'E'
  11681. end
  11682.  
  11683. /*
  11684. **  We want a particular object.
  11685. */
  11686. else
  11687. begin
  11688.     /*
  11689.     **  Now calculate the summary data.
  11690.     **  reserved: sum(reserved) where indid in (0, 1, 255)
  11691.     */
  11692.     insert into #spt_space (reserved)
  11693.         select sum(reserved)
  11694.             from sysindexes
  11695.                 where indid in (0, 1, 255)
  11696.                     and id = @id
  11697.  
  11698.     /*
  11699.     ** data: sum(dpages) where indid < 2
  11700.     **    + sum(used) where indid = 255 (text)
  11701.     */
  11702.     select @pages = sum(dpages)
  11703.             from sysindexes
  11704.                 where indid < 2
  11705.                     and id = @id
  11706.     select @pages = @pages + isnull(sum(used), 0)
  11707.         from sysindexes
  11708.             where indid = 255
  11709.                 and id = @id
  11710.     update #spt_space
  11711.         set data = @pages
  11712.  
  11713.  
  11714.     /* index: sum(used) where indid in (0, 1, 255) - data */
  11715.     update #spt_space
  11716.         set indexp = (select sum(used)
  11717.                 from sysindexes
  11718.                     where indid in (0, 1, 255)
  11719.                         and id = @id)
  11720.                 - data
  11721.  
  11722.     /* unused: sum(reserved) - sum(used) where indid in (0, 1, 255) */
  11723.     update #spt_space
  11724.         set unused = reserved
  11725.                 - (select sum(used)
  11726.                     from sysindexes
  11727.                         where indid in (0, 1, 255)
  11728.                             and id = @id)
  11729.     update #spt_space
  11730.         set rows = i.rows
  11731.             from sysindexes i
  11732.                 where i.indid < 2
  11733.                     and i.id = @id
  11734.  
  11735.     select name = substring(object_name(@id), 1, 20),
  11736.         rows = convert(char(11), rows),
  11737.         reserved = ltrim(str(reserved * d.low / 1024.,15,0) +
  11738.                 ' ' + 'KB'),
  11739.         data = ltrim(str(data * d.low / 1024.,15,0) +
  11740.                 ' ' + 'KB'),
  11741.         index_size = ltrim(str(indexp * d.low / 1024.,15,0) +
  11742.                 ' ' + 'KB'),
  11743.         unused = ltrim(str(unused * d.low / 1024.,15,0) +
  11744.                 ' ' + 'KB')
  11745.     from #spt_space, master.dbo.spt_values d
  11746.         where d.number = 1
  11747.             and d.type = 'E'
  11748. end
  11749.  
  11750. return (0) -- sp_spaceused
  11751. go
  11752.  
  11753. checkpoint
  11754. go
  11755.  
  11756. raiserror(15339,-1,-1,'sp_checktabletempsize')
  11757. go
  11758.  
  11759. create procedure sp_checktabletempsize
  11760.   @objid int,
  11761.   @f_secindexes bit,
  11762.   @total decimal(15) = 0 OUTPUT
  11763. as
  11764.   declare @IndexObjSize decimal(15),
  11765.           @ForwardObjSize decimal(15),
  11766.           @PageObjSize decimal(15),
  11767.           @TextObjSize decimal(15),
  11768.       @overhead decimal(15),
  11769.           @indextotal decimal(15),
  11770.           @pagetotal decimal(15),
  11771.           @texttotal decimal(15),
  11772.           @forwardtotal decimal(15),
  11773.           @query varchar(500)
  11774.  
  11775.   set @overhead = 20    
  11776.   set @IndexObjSize = 100 + @overhead
  11777.   set @ForwardObjSize = 52 + @overhead
  11778.   set @PageObjSize = 44 + @overhead
  11779.   set @TextObjSize = 72 + @overhead
  11780.  
  11781.   /* Index Objects */
  11782.   /* status & 32 detects hypothetical indexes,
  11783.      status & 8  detects dummy tables */
  11784.   select @indextotal = sum(((maxirow*2) + @IndexObjSize) * CAST(dpages as decimal(15)) * 3)
  11785.   from sysindexes
  11786.   where indid > 0 and
  11787.     indid < 255 and
  11788.     id = @objid and
  11789.     ((@f_secindexes = 1) or id = 1) and
  11790.     (status & 32 = 0) and
  11791.     (status & 8 = 0)
  11792.   if @indextotal is null
  11793.     set @indextotal = 0
  11794.  
  11795.   /* Page Objects */ 
  11796.   select @pagetotal = sum((CAST(used as decimal(15)) + (reserved % 8) + (reserved / 8)) * @PageObjSize * 2)
  11797.   from sysindexes
  11798.   where id = @objid and
  11799.     used < 4096
  11800.   if @pagetotal is null
  11801.     set @pagetotal = 0
  11802.  
  11803.   /* Text Objects */
  11804.   select @texttotal = sum(totals.total)
  11805.   from
  11806.     (select (CAST((si1.rows * count(sc.id)) as decimal(15))+ CAST((si2.used * 2) as decimal(15))) * @TextObjSize * 2 as total
  11807.      from sysindexes si1, sysindexes si2, syscolumns sc
  11808.      where si1.id = si2.id and
  11809.            si1.indid in (0,1) and
  11810.            si2.indid = 255 and
  11811.            sc.id = si1.id and
  11812.            sc.xtype in (34,99,35) and
  11813.            si1.id = @objid
  11814.      group by si1.id, si1.rows, si2.used
  11815.     ) totals
  11816.   if @texttotal is null
  11817.     set @texttotal = 0
  11818.  
  11819.   /* Forward Objects */
  11820.   select @forwardtotal = sum((rows/100) * @ForwardObjSize * 2)
  11821.   from sysindexes where indid = 0
  11822.     and id = @objid
  11823.  
  11824.   if @forwardtotal is null
  11825.     set @forwardtotal = 0
  11826.  
  11827.   /* The 1.1 is a "fudge factor" for extra page overhead */
  11828.   set @total = CAST(((@indextotal + @pagetotal + @texttotal + @forwardtotal) * 1.1) as decimal(15))
  11829.   /* the 1.4 is another "fudge factor" */
  11830.   set @total = CAST((@total * 1.4) as decimal(15)) / 1024
  11831. go
  11832.  
  11833. checkpoint
  11834. go
  11835.  
  11836. raiserror(15339,-1,-1,'sp_checkdbtempsize')
  11837. go
  11838.  
  11839. create procedure sp_checkdbtempsize
  11840.   @maxtempdb decimal(15) = 0 OUTPUT
  11841. as
  11842.   declare @objs cursor,
  11843.     @id int,
  11844.     @hold decimal(15),
  11845.     @total decimal(15),
  11846.     @textEst decimal(15),
  11847.     @pageEst decimal(15),
  11848.     @indexEst decimal(15),
  11849.     @totalEst decimal(15),
  11850.     @tet int,
  11851.     @pet int,
  11852.     @iet int,
  11853.     @objstat int,
  11854.     @clust int,
  11855.     @max decimal(15)
  11856.   set @total = 0
  11857.   set @textEst = 0
  11858.   set @pageEst = 0
  11859.   set @indexEst = 0
  11860.   set @max = 0
  11861.  
  11862.   /* @objs is a cursor to walk through sysobjects */
  11863.   set @objs = cursor forward_only static read_only for
  11864.     select id,status from sysobjects where xtype = 'U' or xtype = 'S'
  11865.     order by id
  11866.   open @objs
  11867.   fetch next from @objs into @id, @objstat
  11868.   while (@@fetch_status = 0)
  11869.     begin
  11870.       /* update our page estimate + index + text estimate...
  11871.        * we store the update values in temporary variables just in case they
  11872.        * turn out to be NULL. */
  11873.       select @iet = dpages,
  11874.         @tet = rows,
  11875.         @clust = indid
  11876.       from sysindexes
  11877.       where id = @id and
  11878.         (indid in (0,1))
  11879.       
  11880.       /* update our text estimate.. table contains text if @objstat has 0x00000004 set... (TAB_TEXTIMAGE)
  11881.        * Our estimate is based on the # of rows in the table */
  11882.       if ((@objstat & 4) != 0) and (@tet is not null)
  11883.         set @textEst = @textEst + @tet
  11884.       /* As long as @iet isn't NULL it is safe to update.
  11885.        * We only add to the index estimate if the index is clustered */
  11886.       if (@iet is not null)
  11887.         begin
  11888.           if (@clust = 1)
  11889.             set @indexEst = @indexEst + @iet
  11890.           set @pageEst = @pageEst + @iet
  11891.         end
  11892.  
  11893.       /* now add sec indexes */
  11894.       select @pet = sum(used)
  11895.       from sysindexes
  11896.       where indid > 1 and indid < 255 and
  11897.         id = @id and
  11898.         (status & 32 = 0) and
  11899.         (status & 8 = 0)
  11900.  
  11901.       /* again check for NULL so we can safely add */
  11902.       if (@pet is not null)
  11903.         begin
  11904.           set @pageEst = @pageEst + @pet
  11905.           set @indexEst = @indexEst + @pet
  11906.         end
  11907.  
  11908.       /* this total should at all times match the estimate generated in CheckTables */
  11909.       set @totalEst = CAST(((@textEst / 8) + (@indexEst / 2) + (@pageEst / 16)) as int)
  11910.       /* we put the estimated size for checking our current object into @hold */
  11911.       execute .dbo.sp_checktabletempsize @id,1,@hold OUTPUT
  11912.       set @total = @total + @hold
  11913.       /* if @totalEst is more than 4096 then the scan will be partitioned.  So we store
  11914.        * off our calcualted size and reset our iterators. */
  11915.       if (@totalEst > 4096)
  11916.         begin
  11917.           if (@total > @max)
  11918.             set @max = @total
  11919.           set @total = 0
  11920.           set @textEst = 0
  11921.           set @indexEst = 0
  11922.           set @pageEst = 0
  11923.         end
  11924.       fetch next from @objs into @id, @objstat
  11925.     end
  11926.   close @objs
  11927.   deallocate @objs
  11928.   if (@total > @max)
  11929.     set @max = @total
  11930.   print "TOTAL: " + CAST(@max as varchar) + "KB"
  11931.   set @maxtempdb = @max
  11932. go
  11933.  
  11934. checkpoint
  11935. go
  11936.  
  11937.  
  11938. raiserror(15339,-1,-1,'sp_sqlexec')
  11939.  
  11940. -- sp_sqlexec should not be allowed to update system catalog 
  11941. exec sp_configure 'allow updates',0
  11942. reconfigure with override
  11943. go
  11944.  
  11945. create procedure sp_sqlexec --- 1996/04/08 00:00
  11946.     @p1 text
  11947. as
  11948. exec(@p1)
  11949. go
  11950.  
  11951. exec sp_configure 'allow updates',1
  11952. reconfigure with override
  11953.  
  11954. go
  11955.  
  11956.  
  11957. raiserror(15339,-1,-1,'sp_unbindefault')
  11958. go
  11959. create procedure sp_unbindefault --- 1996/08/13 13:34
  11960. @objname nvarchar(776),         /* table/column or datatype name */
  11961. @futureonly varchar(15) = NULL   /* flag to indicate extent of binding */
  11962. as
  11963.  
  11964. declare @futurevalue varchar(15) /* the value of @futureonly that causes
  11965.                ** the binding to be limited */
  11966.  
  11967. declare
  11968.     @vc1            nvarchar(517)
  11969. declare
  11970.     @tab_id            integer
  11971.     ,@cur_tab_id    integer
  11972.     ,@colid            integer
  11973.     ,@cdefault        integer
  11974.     ,@olddefault    integer
  11975.     ,@xusertype        smallint
  11976.  
  11977.     ,@UnqualObj        sysname
  11978.     ,@QualObj1        sysname
  11979.     ,@QualObj2        sysname
  11980.     ,@QualObj3        sysname
  11981.  
  11982. set cursor_close_on_commit    off
  11983. select @futurevalue = 'futureonly'  /* initialize @futurevalue */
  11984.  
  11985. /*
  11986. **  When a default or rule is bound to a user-defined datatype, it is also
  11987. **  bound, by default, to any columns of the user datatype that are currently
  11988. **  using the existing default or rule as their default or rule.  This default
  11989. **  action may be overridden by setting @futureonly = @futurevalue when the
  11990. **  procedure is invoked.  In this case existing columns with the user
  11991. **  datatype won't have their existing default or rule changed.
  11992. */
  11993.  
  11994. -- get name parts --
  11995. select @UnqualObj = parsename(@objname, 1),
  11996.         @QualObj1 = parsename(@objname, 2),
  11997.         @QualObj2 = parsename(@objname, 3),
  11998.         @QualObj3 = parsename(@objname, 4)
  11999.  
  12000. IF (@UnqualObj is NULL OR @QualObj3 is not null)
  12001.    begin
  12002.    raiserror(15253,-1,-1,@objname)
  12003.    return (1)
  12004.    end
  12005.  
  12006.  
  12007. ------------------  Verify database.
  12008.  
  12009. if (@QualObj2 is not null and @QualObj1 is null)
  12010.     begin
  12011.         raiserror(15084,-1,-1)
  12012.         return (1)
  12013.     end
  12014.  
  12015. /*
  12016. **  If @objname is of the form tab.col then we are unbinding a column.
  12017. **  Otherwise its a datatype.  In the column case, we need to extract
  12018. **  and verify the table and column names and make sure the user owns
  12019. **  the table that is getting the default unbound.
  12020. */
  12021. if @QualObj1 is not null
  12022. begin
  12023.     if (@QualObj2 is not null)
  12024.         select @vc1 = QuoteName(@QualObj2) + '.' + QuoteName(@QualObj1)
  12025.     else
  12026.         select @vc1 = QuoteName(@QualObj1)
  12027.  
  12028.    /*
  12029.    **  Find it and unbind it.
  12030.    */
  12031.    select @tab_id = c.id, @colid = c.colid, @cdefault = c.cdefault
  12032.    from syscolumns c, sysobjects o 
  12033.       where c.id = o.id
  12034.          and c.name = @UnqualObj
  12035.          and o.id = object_id(@vc1,'local')
  12036.          and o.xtype = 'U '
  12037.  
  12038.     if @tab_id is null
  12039.     begin
  12040.          raiserror(15104,-1,-1,@QualObj1,@UnqualObj)
  12041.          return(1)
  12042.     end
  12043.  
  12044.     if @cdefault = 0
  12045.     begin
  12046.         raiserror(15236,-1,-1,@objname)
  12047.         return(1)
  12048.     end
  12049.  
  12050.     if exists
  12051.     (select    *
  12052.         from    sysobjects o
  12053.         where    @cdefault    = o.id
  12054.             and    @tab_id        = o.parent_obj)
  12055.         begin
  12056.             raiserror(15049,-1,-1, @objname)
  12057.             return (1)
  12058.         end
  12059.  
  12060.     BEGIN TRANSACTION txn_unbindefault_1
  12061.  
  12062.          /*
  12063.          **  Since binding a default is a schema change,
  12064.          **  update schema count
  12065.          **  for the object in the sysobjects table.
  12066.          */
  12067.         dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  12068.  
  12069.         update syscolumns set cdefault = 0
  12070.             from syscolumns where id = @tab_id and colid = @colid
  12071.  
  12072.     COMMIT TRANSACTION txn_bindefault_1
  12073.  
  12074.     raiserror(15519,-1,-1)
  12075.     return (0)
  12076.  
  12077. end
  12078.  
  12079. else
  12080.  
  12081. begin
  12082.    /*
  12083.    **  We're unbinding to a user type.  In this case, the @objname
  12084.    **  is really the name of the user datatype.
  12085.    **  When we unbind to a user type, any existing columns get changed
  12086.    **  to the new binding unless their current binding is not equal
  12087.    **  to the current binding for the usertype or if they set the
  12088.    **  @futureonly parameter to @futurevalue.
  12089.    */
  12090.  
  12091.    /*
  12092.    **  Get the current default for the datatype.
  12093.    */
  12094.    select @olddefault = tdefault, @xusertype = xusertype
  12095.         from systypes where name = @UnqualObj and xusertype > 256
  12096.         AND (is_member('db_owner') = 1 OR is_member('db_ddladmin') = 1 OR is_member(user_name(uid))=1)
  12097.  
  12098.    if @olddefault is null
  12099.       begin
  12100.          raiserror(15036,-1,-1,@UnqualObj)
  12101.          return (1)
  12102.       end
  12103.  
  12104.    if @olddefault = 0
  12105.       begin
  12106.          raiserror(15237,-1,-1,@UnqualObj)
  12107.          return (1)
  12108.       end
  12109.  
  12110.    update systypes set tdefault = 0
  12111.       from systypes
  12112.       where xusertype = @xusertype
  12113.  
  12114.    raiserror(15520,-1,-1)
  12115.  
  12116.    /*
  12117.    **  Now see if there are any columns with the usertype that
  12118.    **  need the new binding.
  12119.    */
  12120.    if isnull(@futureonly, ' ') <> @futurevalue
  12121.    begin
  12122.         declare csr_unbindefault_1 insensitive cursor for
  12123.             select
  12124.             distinct
  12125.                  c.id
  12126.                 ,c.colid
  12127.             from     syscolumns c JOIN sysobjects o ON c.id = o.id AND o.xtype = 'U '
  12128.                  where  c.xusertype = @xusertype
  12129.                     and c.cdefault = @olddefault
  12130.             order by c.id
  12131.                     for read only
  12132.  
  12133.         open csr_unbindefault_1
  12134.  
  12135.         fetch next from csr_unbindefault_1 into
  12136.             @tab_id
  12137.             ,@colid
  12138.  
  12139.         BEGIN TRANSACTION txn_unbindefault_2
  12140.  
  12141.             while @@fetch_status = 0
  12142.             begin
  12143.  
  12144.                 select @vc1 = quotename(user_name(OBJECTPROPERTY(@tab_id,'OwnerId'))) + '.' 
  12145.                 + quotename(object_name(@tab_id))
  12146.  
  12147.                 dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  12148.  
  12149.                 select @cur_tab_id = @tab_id
  12150.  
  12151.                 while @cur_tab_id = @tab_id and @@fetch_status = 0
  12152.                 begin
  12153.                       update syscolumns set cdefault = 0
  12154.                     from syscolumns
  12155.                     where id = @tab_id and colid = @colid
  12156.  
  12157.                     fetch next from csr_unbindefault_1 into
  12158.                         @tab_id
  12159.                         ,@colid        
  12160.                 end
  12161.             end --loop 3      /*
  12162.  
  12163.         COMMIT TRANSACTION txn_unbindefault_2
  12164.  
  12165.         deallocate csr_unbindefault_1
  12166.  
  12167.         raiserror(15521,-1,-1)
  12168.     end
  12169. end
  12170.  
  12171. return (0) -- sp_unbindefault
  12172. go
  12173.  
  12174. raiserror(15339,-1,-1,'sp_unbindrule')
  12175. go
  12176. create procedure sp_unbindrule --- 1996/08/13 13:33
  12177. @objname nvarchar(776),         /* table/column or datatype name */
  12178. @futureonly varchar(15) = NULL      /* flag to indicate extent of binding */
  12179. as
  12180.  
  12181. declare @oldrule int /* current rule for type */
  12182. declare @tabname sysname     /* name of table */
  12183. declare @colname sysname     /* name of column */
  12184. declare @futurevalue varchar(15) /* the value of @futureonly that causes
  12185.                            ** the binding to be limited */
  12186.  
  12187. declare
  12188.     @vc1            nvarchar(517)
  12189. declare
  12190.      @obj_id        integer
  12191.     ,@cur_tab_id    integer
  12192.     ,@colid            integer
  12193.     ,@domain        integer
  12194.     ,@xusertype        smallint
  12195.  
  12196.     ,@owner_name    sysname
  12197.     ,@obj_name        sysname
  12198.  
  12199.     ,@UnqualObj            sysname
  12200.     ,@QualObj1            sysname
  12201.     ,@QualObj2            sysname
  12202.     ,@QualObj3            sysname
  12203.  
  12204. set cursor_close_on_commit    off
  12205.  
  12206. select @futurevalue = 'futureonly'  /* initialize @futurevalue */
  12207.  
  12208. /*
  12209. **  When a default or rule is bound to a user-defined datatype, it is also
  12210. **  bound, by default, to any columns of the user datatype that are currently
  12211. **  using the existing default or rule as their default or rule.  This default
  12212. **  action may be overridden by setting @futureonly = @futurevalue when the
  12213. **  procedure is invoked.  In this case existing columns with the user
  12214. **  datatype won't have their existing default or rule changed.
  12215. */
  12216.  
  12217. -- get name parts --
  12218. select @UnqualObj = parsename(@objname, 1),
  12219.         @QualObj1 = parsename(@objname, 2),
  12220.         @QualObj2 = parsename(@objname, 3),
  12221.         @QualObj3 = parsename(@objname, 4)
  12222.  
  12223. IF (@UnqualObj is NULL OR @QualObj3 is not null)
  12224.    begin
  12225.    raiserror(15253,-1,-1,@objname)
  12226.    return (1)
  12227.    end
  12228.  
  12229.  
  12230. ------------------  Verify database.
  12231.  
  12232. if (@QualObj2 is not null and @QualObj1 is null)
  12233.     begin
  12234.         raiserror(15084,-1,-1)
  12235.         return (1)
  12236.     end
  12237.  
  12238. /*
  12239. **  If @objname is of the form tab.col then we are unbinding a column.
  12240. **  Otherwise its a datatype.  In the column case, we need to extract
  12241. **  and verify the table and column names and make sure the user owns
  12242. **  the table that is getting the default unbound.
  12243. */
  12244. if @QualObj1 is not null
  12245. begin
  12246.     if (@QualObj2 is not null)
  12247.         select @vc1 = QuoteName(@QualObj2) + '.' + QuoteName(@QualObj1)
  12248.     else
  12249.         select @vc1 = QuoteName(@QualObj1)
  12250.  
  12251.     select    @obj_id = c.id,    @colid = c.colid,    @domain = c.domain
  12252.         from syscolumns c, sysobjects o
  12253.     where c.id = o.id
  12254.     and c.name = @UnqualObj
  12255.     and o.id = object_id(@vc1,'local')
  12256.     and o.xtype = 'U '
  12257.  
  12258.     if @obj_id is null
  12259.     begin
  12260.         raiserror(15104,-1,-1,@QualObj1,@UnqualObj)
  12261.         return (1)
  12262.     end
  12263.  
  12264.     if @domain = 0
  12265.     begin
  12266.         raiserror(15238,-1,-1,@objname)
  12267.         return (1)
  12268.     end
  12269.  
  12270.     BEGIN TRANSACTION txn_unbindrule_1
  12271.  
  12272.         /*
  12273.         **  Update schema count
  12274.         **  for the object in the sysobjects table.
  12275.         */
  12276.  
  12277.         dbcc LockObjectSchema(@vc1) -- Locks Object and increments schema_ver.
  12278.  
  12279.         update syscolumns set domain = 0
  12280.             from syscolumns c where id = @obj_id and colid = @colid
  12281.  
  12282.     COMMIT TRANSACTION txn_unbindrule_1
  12283.  
  12284.     raiserror(15522,-1,-1)
  12285.  
  12286. end
  12287. else
  12288. begin
  12289.  
  12290.     select @oldrule = domain, @xusertype = xusertype
  12291.         from systypes where name = @UnqualObj and xusertype > 256
  12292.         AND (is_member('db_owner') = 1 OR is_member('db_ddladmin') = 1 OR is_member(user_name(uid))=1)
  12293.  
  12294.     if @xusertype is null
  12295.     begin
  12296.         raiserror(15036,-1,-1,@UnqualObj)
  12297.         return (1)
  12298.     end
  12299.  
  12300.     if @oldrule = 0
  12301.     begin
  12302.         raiserror(15239,-1,-1,@UnqualObj)
  12303.         return (1)
  12304.     end
  12305.  
  12306.     update systypes set domain = 0
  12307.     from systypes
  12308.     where xusertype = @xusertype
  12309.  
  12310.     raiserror(15523,-1,-1)
  12311.  
  12312.     if isnull(@futureonly, ' ') <> @futurevalue
  12313.     begin
  12314.  
  12315.         declare csr_unbindrule_1 insensitive cursor for
  12316.         select
  12317.             distinct
  12318.              o.id
  12319.             ,user_name(o.uid)
  12320.             ,o.name
  12321.             ,c.colid
  12322.         from    syscolumns c
  12323.             ,sysobjects o
  12324.          where o.id = c.id and o.xtype = 'U '
  12325.             and c.xusertype = @xusertype
  12326.             and c.domain = @oldrule
  12327.         order by o.id
  12328.             for read only
  12329.  
  12330.         open csr_unbindrule_1
  12331.  
  12332.  
  12333.         BEGIN TRANSACTION txn_unbindrule_2
  12334.  
  12335.             fetch next from csr_unbindrule_1 into
  12336.             @obj_id
  12337.             ,@owner_name
  12338.             ,@obj_name
  12339.             ,@colid
  12340.  
  12341.             while @@fetch_status = 0
  12342.             begin
  12343.  
  12344.                 select @vc1 = quotename(@owner_name) + '.' + quotename(@obj_name)
  12345.  
  12346.                 dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  12347.  
  12348.                 select @cur_tab_id = @obj_id
  12349.  
  12350.                 while @cur_tab_id = @obj_id and @@fetch_status = 0
  12351.                 begin
  12352.                       update syscolumns set domain = 0
  12353.                     from syscolumns
  12354.                     where id = @obj_id and colid = @colid
  12355.  
  12356.                     fetch next from csr_unbindrule_1 into
  12357.                     @obj_id
  12358.                     ,@owner_name
  12359.                     ,@obj_name
  12360.                     ,@colid    
  12361.                 end
  12362.             end
  12363.  
  12364.         COMMIT TRANSACTION txn_unbindrule_2
  12365.         deallocate csr_unbindrule_1
  12366.         raiserror(15524,-1,-1)
  12367.  
  12368.     end
  12369. end
  12370.  
  12371. return (0)    --sp_unbindrule
  12372. go
  12373.  
  12374.  
  12375. checkpoint
  12376. go
  12377.  
  12378. --
  12379. raiserror(15339,-1,-1,'sp_who')
  12380. go
  12381. create procedure sp_who  --- 1995/11/28 15:48
  12382.        @loginame sysname = NULL --or 'active'
  12383. as
  12384.  
  12385. declare     @spidlow    int,
  12386.          @spidhigh    int,
  12387.          @spid        int,
  12388.          @sid        varbinary(85)
  12389.  
  12390. select     @spidlow    =     0
  12391.         ,@spidhigh    = 32767
  12392.  
  12393.  
  12394. if (    @loginame is not NULL
  12395.    AND    upper(@loginame) = 'ACTIVE'
  12396.    )
  12397.     begin
  12398.  
  12399.     select spid ,status
  12400.               ,loginame=rtrim(loginame)
  12401.           ,hostname ,blk=convert(char(5),blocked)
  12402.           ,dbname= db_name(dbid),cmd
  12403.     from  master.dbo.sysprocesses
  12404.     where spid >= @spidlow and spid <= @spidhigh AND
  12405.           upper(cmd) <> 'AWAITING COMMAND'
  12406.  
  12407.     return (0)
  12408.     end
  12409.  
  12410. if (@loginame is not NULL
  12411.    AND    upper(@loginame) <> 'ACTIVE'
  12412.    )
  12413. begin
  12414.     if (@loginame like '[0-9]%')    -- is a spid.
  12415.     begin
  12416.         select @spid = convert(int, @loginame)
  12417.         select spid, status,
  12418.                loginame=rtrim(loginame),
  12419.                hostname,blk = convert(char(5),blocked),
  12420.                dbname=db_name(dbid),
  12421.                cmd
  12422.         from  master.dbo.sysprocesses
  12423.         where spid = @spid
  12424.     end
  12425.     else
  12426.     begin
  12427.         select @sid = suser_sid(@loginame)
  12428.         if (@sid is null)
  12429.         begin
  12430.             raiserror(15007,-1,-1,@loginame)
  12431.             return (1)
  12432.         end        
  12433.         select spid, status,
  12434.                loginame=rtrim(loginame),
  12435.                hostname ,blk=convert(char(5),blocked),
  12436.                dbname=db_name(dbid),
  12437.                cmd
  12438.         from  master.dbo.sysprocesses
  12439.         where sid = @sid
  12440.     end
  12441.     return (0)
  12442. end
  12443.  
  12444.  
  12445. /* loginame arg is null */
  12446. select spid,
  12447.        status,
  12448.        loginame=rtrim(loginame),
  12449.        hostname,
  12450.        blk=convert(char(5),blocked),
  12451.        dbname=db_name(dbid),
  12452.        cmd
  12453. from  master.dbo.sysprocesses
  12454. where spid >= @spidlow and spid <= @spidhigh
  12455.  
  12456.  
  12457. return (0) -- sp_who
  12458. go
  12459.  
  12460.  
  12461.  
  12462. raiserror(15339,-1,-1,'sp_who2')
  12463. go
  12464. CREATE PROCEDURE sp_who2  --- 1995/11/03 10:16
  12465.     @loginame     sysname = NULL
  12466. as
  12467.  
  12468. set nocount on
  12469.  
  12470. declare
  12471.     @retcode         int
  12472.  
  12473. declare
  12474.     @sidlow         varbinary(85)
  12475.    ,@sidhigh        varbinary(85)
  12476.    ,@sid1           varbinary(85)
  12477.    ,@spidlow         int
  12478.    ,@spidhigh        int
  12479.  
  12480. declare
  12481.     @charMaxLenLoginName      varchar(6)
  12482.    ,@charMaxLenDBName         varchar(6)
  12483.    ,@charMaxLenCPUTime        varchar(10)
  12484.    ,@charMaxLenDiskIO         varchar(10)
  12485.    ,@charMaxLenHostName       varchar(10)
  12486.    ,@charMaxLenProgramName    varchar(10)
  12487.    ,@charMaxLenLastBatch      varchar(10)
  12488.    ,@charMaxLenCommand        varchar(10)
  12489.  
  12490. declare
  12491.     @charsidlow              varchar(85)
  12492.    ,@charsidhigh             varchar(85)
  12493.    ,@charspidlow              varchar(11)
  12494.    ,@charspidhigh             varchar(11)
  12495.  
  12496. --------
  12497.  
  12498. select
  12499.     @retcode         = 0      -- 0=good ,1=bad.
  12500.  
  12501. --------defaults
  12502. select @sidlow = convert(varbinary(85), (replicate(char(0), 85)))
  12503. select @sidhigh = convert(varbinary(85), (replicate(char(1), 85)))
  12504.  
  12505. select
  12506.     @spidlow         = 0
  12507.    ,@spidhigh        = 32767
  12508.  
  12509. --------------------------------------------------------------
  12510. IF (@loginame IS     NULL)  --Simple default to all LoginNames.
  12511.       GOTO LABEL_17PARM1EDITED
  12512.  
  12513. --------
  12514.  
  12515. -- select @sid1 = suser_sid(@loginame)
  12516. select @sid1 = null
  12517. if exists(select * from master.dbo.syslogins where loginname = @loginame)
  12518.     select @sid1 = sid from master.dbo.syslogins where loginname = @loginame
  12519.  
  12520. IF (@sid1 IS NOT NULL)  --Parm is a recognized login name.
  12521.    begin
  12522.    select @sidlow  = suser_sid(@loginame)
  12523.          ,@sidhigh = suser_sid(@loginame)
  12524.    GOTO LABEL_17PARM1EDITED
  12525.    end
  12526.  
  12527. --------
  12528.  
  12529. IF (lower(@loginame) IN ('active'))  --Special action, not sleeping.
  12530.    begin
  12531.    select @loginame = lower(@loginame)
  12532.    GOTO LABEL_17PARM1EDITED
  12533.    end
  12534.  
  12535. --------
  12536.  
  12537. IF (patindex ('%[^0-9]%' , isnull(@loginame,'z')) = 0)  --Is a number.
  12538.    begin
  12539.    select
  12540.              @spidlow   = convert(int, @loginame)
  12541.             ,@spidhigh  = convert(int, @loginame)
  12542.    GOTO LABEL_17PARM1EDITED
  12543.    end
  12544.  
  12545. --------
  12546.  
  12547. RaisError(15007,-1,-1,@loginame)
  12548. select @retcode = 1
  12549. GOTO LABEL_86RETURN
  12550.  
  12551.  
  12552. LABEL_17PARM1EDITED:
  12553.  
  12554.  
  12555. --------------------  Capture consistent sysprocesses.  -------------------
  12556.  
  12557. SELECT
  12558.  
  12559.   spid
  12560.  ,status
  12561.  ,sid
  12562.  ,hostname
  12563.  ,program_name
  12564.  ,cmd
  12565.  ,cpu
  12566.  ,physical_io
  12567.  ,blocked
  12568.  ,dbid
  12569.  ,convert(sysname, rtrim(loginame))
  12570.         as loginname
  12571.  ,spid as 'spid_sort'
  12572.  
  12573.  ,  substring( convert(varchar,last_batch,111) ,6  ,5 ) + ' '
  12574.   + substring( convert(varchar,last_batch,113) ,13 ,8 )
  12575.        as 'last_batch_char'
  12576.  
  12577.       INTO    #tb1_sysprocesses
  12578.       from master.dbo.sysprocesses   (nolock)
  12579.  
  12580.  
  12581.  
  12582. --------Screen out any rows?
  12583.  
  12584. IF (@loginame IN ('active'))
  12585.    DELETE #tb1_sysprocesses
  12586.          where   lower(status)  = 'sleeping'
  12587.          and     upper(cmd)    IN (
  12588.                      'AWAITING COMMAND'
  12589.                     ,'MIRROR HANDLER'
  12590.                     ,'LAZY WRITER'
  12591.                     ,'CHECKPOINT SLEEP'
  12592.                     ,'RA MANAGER'
  12593.                                   )
  12594.  
  12595.          and     blocked       = 0
  12596.  
  12597.  
  12598.  
  12599. --------Prepare to dynamically optimize column widths.
  12600.  
  12601.  
  12602. Select
  12603.     @charsidlow     = convert(varchar(85),@sidlow)
  12604.    ,@charsidhigh    = convert(varchar(85),@sidhigh)
  12605.    ,@charspidlow     = convert(varchar,@spidlow)
  12606.    ,@charspidhigh    = convert(varchar,@spidhigh)
  12607.  
  12608.  
  12609.  
  12610. SELECT
  12611.              @charMaxLenLoginName =
  12612.                   convert( varchar
  12613.                           ,isnull( max( datalength(loginname)) ,5)
  12614.                          )
  12615.  
  12616.             ,@charMaxLenDBName    =
  12617.                   convert( varchar
  12618.                           ,isnull( max( datalength( convert(varchar,db_name(dbid)))) ,6)
  12619.                          )
  12620.  
  12621.             ,@charMaxLenCPUTime   =
  12622.                   convert( varchar
  12623.                           ,isnull( max( datalength( convert(varchar,cpu))) ,7)
  12624.                          )
  12625.  
  12626.             ,@charMaxLenDiskIO    =
  12627.                   convert( varchar
  12628.                           ,isnull( max( datalength( convert(varchar,physical_io))) ,6)
  12629.                          )
  12630.  
  12631.             ,@charMaxLenCommand  =
  12632.                   convert( varchar
  12633.                           ,isnull( max( datalength( convert(varchar,cmd))) ,7)
  12634.                          )
  12635.  
  12636.             ,@charMaxLenHostName  =
  12637.                   convert( varchar
  12638.                           ,isnull( max( datalength( convert(varchar,hostname))) ,8)
  12639.                          )
  12640.  
  12641.             ,@charMaxLenProgramName =
  12642.                   convert( varchar
  12643.                           ,isnull( max( datalength( convert(varchar,program_name))) ,11)
  12644.                          )
  12645.  
  12646.             ,@charMaxLenLastBatch =
  12647.                   convert( varchar
  12648.                           ,isnull( max( datalength( convert(varchar,last_batch_char))) ,9)
  12649.                          )
  12650.       from
  12651.              #tb1_sysprocesses
  12652.       where
  12653. --             sid >= @sidlow
  12654. --      and    sid <= @sidhigh
  12655. --      and
  12656.              spid >= @spidlow
  12657.       and    spid <= @spidhigh
  12658.  
  12659.  
  12660.  
  12661. --------Output the report.
  12662.  
  12663.  
  12664. EXECUTE(
  12665. '
  12666. SET nocount off
  12667.  
  12668. SELECT
  12669.              SPID          = convert(char(5),spid)
  12670.  
  12671.             ,Status        =
  12672.                   CASE lower(status)
  12673.                      When ''sleeping'' Then lower(status)
  12674.                      Else                   upper(status)
  12675.                   END
  12676.  
  12677.             ,Login         = substring(loginname,1,' + @charMaxLenLoginName + ')
  12678.  
  12679.             ,HostName      =
  12680.                   CASE hostname
  12681.                      When Null  Then ''  .''
  12682.                      When '' '' Then ''  .''
  12683.                      Else    substring(hostname,1,' + @charMaxLenHostName + ')
  12684.                   END
  12685.  
  12686.             ,BlkBy         =
  12687.                   CASE               isnull(convert(char(5),blocked),''0'')
  12688.                      When ''0'' Then ''  .''
  12689.                      Else            isnull(convert(char(5),blocked),''0'')
  12690.                   END
  12691.  
  12692.             ,DBName        = substring(db_name(dbid),1,' + @charMaxLenDBName + ')
  12693.             ,Command       = substring(cmd,1,' + @charMaxLenCommand + ')
  12694.  
  12695.             ,CPUTime       = substring(convert(varchar,cpu),1,' + @charMaxLenCPUTime + ')
  12696.             ,DiskIO        = substring(convert(varchar,physical_io),1,' + @charMaxLenDiskIO + ')
  12697.  
  12698.             ,LastBatch     = substring(last_batch_char,1,' + @charMaxLenLastBatch + ')
  12699.  
  12700.             ,ProgramName   = substring(program_name,1,' + @charMaxLenProgramName + ')
  12701.             ,SPID          = convert(char(5),spid)  --Handy extra for right-scrolling users.
  12702.       from
  12703.              #tb1_sysprocesses  --Usually DB qualification is needed in exec().
  12704.       where
  12705.              spid >= ' + @charspidlow  + '
  12706.       and    spid <= ' + @charspidhigh + '
  12707.  
  12708.       -- (Seems always auto sorted.)   order by spid_sort
  12709.  
  12710. SET nocount on
  12711. '
  12712. )
  12713. /*****AKUNDONE: removed from where-clause in above EXEC sqlstr
  12714.              sid >= ' + @charsidlow  + '
  12715.       and    sid <= ' + @charsidhigh + '
  12716.       and
  12717. **************/
  12718.  
  12719.  
  12720. LABEL_86RETURN:
  12721.  
  12722.  
  12723. if (object_id('tempdb..#tb1_sysprocesses') is not null)
  12724.             drop table #tb1_sysprocesses
  12725.  
  12726. return @retcode -- sp_who2
  12727. go
  12728.  
  12729.  
  12730.  
  12731. checkpoint
  12732. go
  12733.  
  12734. ---------------------------------------------------------------------------------------------
  12735. ---------------------------------------------------------------------------------------------
  12736. ---------------------------------------------------------------------------------------------
  12737.  
  12738.  
  12739. ---- Create following procs last, since they reference other procedures.
  12740.  
  12741.  
  12742.  
  12743. raiserror(15339,-1,-1,'sp_check_removable')
  12744. go
  12745. create procedure sp_check_removable @autofix varchar(4)
  12746. as
  12747.  
  12748. declare @dbosid varbinary (86)
  12749. declare @dbname sysname
  12750. declare @exec_stmt nvarchar(540)
  12751. declare @fgname sysname
  12752.  
  12753. select @dbname=db_name()
  12754.  
  12755. /* Verify that SA owns the database. */
  12756.  
  12757. select @dbosid = sid from master..sysdatabases where name = @dbname
  12758. if @dbosid <> 0x01
  12759.     if @autofix='auto'
  12760.     begin
  12761.         -- changing DBO to SA
  12762.         update sysdatabases set sid = 0x01
  12763.             where name = @dbname
  12764.         update sysusers set sid = 0x01
  12765.             where uid = 1
  12766.     end
  12767.     else
  12768.     begin
  12769.         raiserror(15258,-1,-1, @dbname)
  12770.         return(1)
  12771.     end
  12772.  
  12773.     -- USE CORRECT non-dbo/guest CHECKING
  12774.     declare @ret int
  12775.     exec @ret = sp_check_removable_sysusers @autofix
  12776.     if @ret <> 0
  12777.         return 1
  12778.  
  12779.     -- Run UPDATE STATISTICS on all user tables if there are
  12780.     -- no user defined filegroups
  12781.     if @autofix='auto' and
  12782.         (select count(*) from sysfilegroups) = 1
  12783.     begin
  12784.         select @exec_stmt = N'USE ' + quotename( @dbname , '[') 
  12785.         + N' exec sp_updatestats ' 
  12786.         exec (@exec_stmt)
  12787.     end
  12788.  
  12789.     exec('dump tran '+@dbname+' with no_log')
  12790.  
  12791.     if (select count(*) from sysfilegroups) > 1
  12792.     begin
  12793.         if @autofix='auto'
  12794.         begin
  12795.             -- Mark any non-primary filegroups as READONLY
  12796.             DECLARE fgcursor INSENSITIVE CURSOR 
  12797.             FOR SELECT groupname FROM sysfilegroups fg 
  12798.                 WHERE fg.groupid > 1 -- not primary
  12799.                 AND fg.status & 0x8 = 0 -- not already readonly
  12800.                 AND (SELECT count (*) FROM sysfiles f WHERE 
  12801.                 f.groupid = fg.groupid) > 0 -- has some files
  12802.             OPEN fgcursor
  12803.             FETCH NEXT FROM fgcursor INTO @fgname
  12804.             WHILE (@@FETCH_STATUS <> -1)
  12805.             BEGIN
  12806.                 SELECT @exec_stmt = 'ALTER DATABASE '
  12807.                 + quotename( @dbname , '[') 
  12808.                 + ' MODIFY FILEGROUP '
  12809.                 + quotename( @fgname , '[')
  12810.                 + ' READONLY'
  12811.                 EXEC (@exec_stmt)
  12812.                 FETCH NEXT FROM fgcursor INTO @fgname
  12813.             END
  12814.             CLOSE fgcursor
  12815.             DEALLOCATE fgcursor
  12816.         end
  12817.         else
  12818.         begin
  12819.             if exists (SELECT groupname FROM sysfilegroups fg 
  12820.                 WHERE fg.groupid > 1 -- not primary
  12821.                 AND fg.status & 0x8 = 0 -- not already readonly
  12822.                 AND (SELECT count (*) FROM sysfiles f WHERE 
  12823.                 f.groupid = fg.groupid) > 0) -- has some files
  12824.             begin
  12825.                 raiserror(15358,-1,-1)
  12826.                 SELECT groupname FROM sysfilegroups fg 
  12827.                     WHERE fg.groupid > 1 -- not primary
  12828.                     AND fg.status & 0x8 = 0 -- not already readonly
  12829.                 return (-1)
  12830.             end 
  12831.         end
  12832.     
  12833.  
  12834.     end
  12835. return(0)
  12836. go
  12837.  
  12838.  
  12839. raiserror(15339,-1,-1,'sp_certify_removable')
  12840. go
  12841. CREATE PROCEDURE sp_certify_removable  --1996/03/12 12:02
  12842.  
  12843.         @dbname sysname,
  12844.         @autofix nvarchar(4) = null
  12845. as
  12846.  
  12847. set nocount on
  12848.  
  12849. declare @ret_value int,
  12850.     @char_autofix varchar(25)
  12851.  
  12852. if suser_id() <> 1      -- Make sure that it is the SA executing this.
  12853.         begin
  12854.                 raiserror(15003,-1,-1, 'sysadmin')
  12855.                 return(1)
  12856.         end
  12857.  
  12858.  
  12859. select @autofix = lower(@autofix)
  12860.  
  12861. if @autofix <> 'auto' and @autofix is not null
  12862.         begin
  12863.                 raiserror(15255,-1,-1,@autofix)
  12864.                 return(1)
  12865.         end
  12866.  
  12867.  
  12868. if @dbname is null      -- Show usage diagram if no dbname supplied.
  12869.         begin
  12870.                 raiserror(15256,-1,-1)
  12871.                 return(1)
  12872.         end
  12873.  
  12874.  
  12875. --See if DB exists.
  12876. if not exists (select * from sysdatabases where name = @dbname)
  12877.         begin
  12878.                 raiserror(15010,-1,-1,@dbname)
  12879.                 return(1)
  12880.         end
  12881.  
  12882.  
  12883. --Cannot take master, tempdb or model databases offline.
  12884. if lower(@dbname) in ('master','tempdb','model')
  12885.         begin
  12886.                 raiserror(15266,-1,-1,@dbname)
  12887.                 return(1)
  12888.         end
  12889.  
  12890.  
  12891. -- Will not be able to take db offline if user is in it.
  12892. if @dbname = db_name()
  12893.         begin
  12894.                 raiserror(15257,-1,-1)
  12895.                 return(1)
  12896.         end
  12897.  
  12898. -------------  Check things that exist only in the db.  -------------------
  12899. select @char_autofix =
  12900.     CASE
  12901.        When @autofix IS NOT Null Then '''Auto'''
  12902.        Else                           'Null'
  12903.     END
  12904.  
  12905. execute(
  12906. 'use ' + @dbname + '
  12907.  
  12908. declare @inx_ret_value int ,@int1 int
  12909. select  @inx_ret_value = 1
  12910.  
  12911. exec @inx_ret_value = sp_check_removable ' + @char_autofix + '
  12912.  
  12913. --Use @@rowcount for a user_assignable global variable for communication.
  12914. if @inx_ret_value <> 0    --bad
  12915.     begin
  12916.     select @int1 = suid from master.dbo.syslogins where sid= 0x01 --SA
  12917.     return
  12918.     end
  12919. else
  12920.     begin
  12921.     select @int1 = suid from master.dbo.syslogins where sid=0x01 and 1=2
  12922.     return
  12923.     end
  12924. '
  12925. )
  12926.  
  12927. if @@rowcount > 0
  12928.         return (1)  --Error was returned by other proc, so exit
  12929.  
  12930.  
  12931. -- Take it offline
  12932. raiserror('' ,0,1)
  12933. exec sp_dboption @dbname,'offline','true'
  12934.  
  12935. return(0)
  12936. go
  12937.  
  12938.  
  12939. print ' '
  12940. raiserror(15339,-1,-1,'MS_sqlctrs_users')
  12941. go
  12942. create procedure MS_sqlctrs_users --- 1996/08/30 21:49
  12943. as
  12944. select
  12945.          lg.loginname + ' - ' + convert(varchar(30),pr.spid)
  12946.         ,pr.memusage        as 'Memory (8K Pages)' -- 2K in 6.5
  12947.         ,pr.cpu            as 'CPU time'
  12948.         ,pr.physical_io
  12949.         ,count(lk.spid)        as 'Locks held'
  12950.         ,pr.spid
  12951.     from
  12952.          master.dbo.sysprocesses    pr    left outer join
  12953.          master.dbo.syslocks    lk    on pr.spid=lk.spid
  12954.         ,master.dbo.syslogins    lg
  12955.     where
  12956.          pr.sid    = lg.sid
  12957.     group by
  12958.          lg.loginname
  12959.         ,pr.spid
  12960.         ,pr.memusage
  12961.         ,pr.cpu
  12962.         ,pr.physical_io
  12963. go
  12964.  
  12965. print ' '
  12966. raiserror(15339,-1,-1,'sp_autostats')
  12967. go
  12968. CREATE PROCEDURE sp_autostats
  12969.     @tblname     nvarchar(776),
  12970.     @flagc        varchar(10)=null,
  12971.     @indname    sysname=null
  12972. AS
  12973. BEGIN
  12974.     DECLARE @flag bit, @nrc_mask int
  12975.     
  12976.     /*
  12977.     **  Check flag
  12978.     */
  12979.     SET @flag = CASE lower(@flagc)
  12980.         WHEN 'on'     THEN 1
  12981.         WHEN 'off'     THEN 0
  12982.         ELSE NULL
  12983.         END
  12984.  
  12985.     IF @flag IS NULL AND @flagc IS NOT NULL
  12986.         BEGIN
  12987.         RAISERROR(17000,-1,-1)
  12988.             RETURN (1)
  12989.         END
  12990.  
  12991.     /*
  12992.     ** Set NORECOMPUTE mask
  12993.     */
  12994.     SET @nrc_mask = 16777216
  12995.  
  12996.     /*
  12997.     ** Check we are executing in the correct database
  12998.     */
  12999.     DECLARE @db sysname
  13000.     SELECT @db = parsename(@tblname, 3)
  13001.  
  13002.     IF (@db IS NOT NULL AND @db <> db_name())
  13003.     BEGIN
  13004.         RAISERROR(15387,-1,-1)
  13005.         RETURN (1)
  13006.     END
  13007.  
  13008.     /*
  13009.     ** PRINT or UPDATE status?
  13010.     */
  13011.     IF (@flag IS NULL) 
  13012.     BEGIN
  13013.  
  13014.         -- Display global settings (sp_dboption)
  13015.         --
  13016.         PRINT 'Global statistics settings for ' + quotename(db_name(), '[') + ':'
  13017.         PRINT '  Automatic update statistics: ' + (CASE WHEN DatabaseProperty(db_name(), 'IsAutoUpdateStatistics') = 1 THEN 'ON' ELSE 'OFF' END)
  13018.         PRINT '  Automatic create statistics: ' + (CASE WHEN DatabaseProperty(db_name(), 'IsAutoCreateStatistics') = 1 THEN 'ON' ELSE 'OFF' END)
  13019.         PRINT ''
  13020.  
  13021.         -- Display the current status of the index(s)
  13022.         --
  13023.         PRINT 'Settings for table ' + quotename(@tblname, '[')
  13024.         PRINT ''
  13025.         SELECT "Index Name" = quotename(si.name, '['),
  13026.                "AUTOSTATS" = 
  13027.             CASE (si.status & @nrc_mask)
  13028.                 WHEN @nrc_mask THEN 'OFF' 
  13029.                 ELSE 'ON' 
  13030.             END,
  13031.                "Last Updated" = stats_date(object_id(@tblname), si.indid)
  13032.         FROM sysindexes si
  13033.         WHERE si.id = object_id(@tblname) AND        -- Table
  13034.               si.indid BETWEEN 1 AND 254 AND        -- Skip HEAP/TEXT index
  13035.             CASE                     -- Match name
  13036.                 WHEN @indname IS NULL THEN 1
  13037.                 WHEN @indname = si.name THEN 1
  13038.                 ELSE 0
  13039.             END = 1
  13040.     END
  13041.     ELSE 
  13042.     BEGIN
  13043.         DECLARE @_rowcount int
  13044.  
  13045.         BEGIN TRANSACTION upd_tran
  13046.  
  13047.         -- Lock the table schema and check permissions
  13048.         --
  13049.         DBCC LOCKOBJECTSCHEMA(@tblname)
  13050.  
  13051.         -- Flip the status bits
  13052.         --
  13053.         DECLARE @batch varchar(8000)
  13054.  
  13055.         UPDATE sysindexes 
  13056.         SET status = 
  13057.             CASE @flag
  13058.             WHEN 1 THEN status &~ @nrc_mask
  13059.             ELSE status | @nrc_mask
  13060.             END
  13061.         WHERE id = object_id(@tblname) AND        -- Table
  13062.               indid <> 255 AND                -- Skip TEXT index
  13063.               CASE                     -- Match name
  13064.             WHEN @indname IS NULL THEN 1
  13065.             WHEN @indname = name THEN 1
  13066.             ELSE 0
  13067.               END = 1
  13068.  
  13069.         -- Save the affected rowcount
  13070.         SET @_rowcount = @@rowcount
  13071.  
  13072.         COMMIT TRANSACTION upd_tran
  13073.  
  13074.         -- Show the user how many indices were affected
  13075.         PRINT 'Automatic statistics maintenance turned ' + 
  13076.             CASE @flag WHEN 1 THEN 'ON' ELSE 'OFF' END +
  13077.             ' for ' + convert(varchar(5), @_rowcount) + 
  13078.             ' indices.'
  13079.  
  13080.     END
  13081.     
  13082.     -- All done
  13083.     --
  13084.     RETURN(0) -- sp_autostats
  13085. END
  13086. GO
  13087.  
  13088. raiserror(15339,-1,-1,'sp_updatestats')
  13089. go
  13090. CREATE PROCEDURE sp_updatestats
  13091. AS
  13092.  
  13093.     DECLARE @dbsid varbinary(85)
  13094.  
  13095.     SELECT  @dbsid = sid 
  13096.     FROM master.dbo.sysdatabases
  13097.     WHERE name = db_name()
  13098.  
  13099.     /*Check the user sysadmin*/
  13100.      IF NOT is_srvrolemember('sysadmin') = 1 AND suser_sid() <> @dbsid
  13101.         BEGIN
  13102.             RAISERROR(15288,-1,-1,'SA or DBO','sp_updatestats')
  13103.             RETURN (1)
  13104.         END
  13105.  
  13106.     DECLARE @exec_stmt nvarchar(540)
  13107.     DECLARE @tablename sysname
  13108.     DECLARE @uid smallint
  13109.     DECLARE @user_name sysname
  13110.     DECLARE @tablename_header varchar(267)
  13111.     DECLARE tnames_cursor CURSOR FOR SELECT name, uid FROM sysobjects WHERE type = 'U' 
  13112.     OPEN tnames_cursor
  13113.     FETCH NEXT FROM tnames_cursor INTO @tablename, @uid
  13114.     WHILE (@@fetch_status <> -1)
  13115.     BEGIN
  13116.         IF (@@fetch_status <> -2)
  13117.         BEGIN
  13118.             SELECT @user_name = user_name(@uid)
  13119.             SELECT @tablename_header = 'Updating ' + @user_name +'.'+ RTRIM(LOWER(@tablename))
  13120.             PRINT @tablename_header
  13121.             SELECT @exec_stmt = 'UPDATE STATISTICS ' + quotename( @user_name , '[')+'.' + quotename( @tablename, '[')
  13122.             EXEC (@exec_stmt)
  13123.         END
  13124.         FETCH NEXT FROM tnames_cursor INTO @tablename, @uid
  13125.     END
  13126.     PRINT ' '
  13127.     PRINT ' '
  13128.     raiserror(15005,-1,-1)
  13129.     DEALLOCATE tnames_cursor
  13130.     RETURN(0) -- sp_updatestats
  13131. go
  13132.  
  13133. -------------------------------- sp_createstats --------begin---------------------------
  13134.  raiserror(15339,-1,-1,'sp_createstats')
  13135. go
  13136.  
  13137.  
  13138. CREATE PROCEDURE sp_createstats
  13139. @indexonly CHAR(9)= 'NO',     -- Optional 'INDEXONLY' text - if present, then only the columns 
  13140.                 -- covered by indexes are subject of statistics creation
  13141. @fullscan  CHAR(9)= 'NO',      -- Optional 'FULLSCAN' text - if present, then the statistics 
  13142.                 -- will be updated with full scan rather than sampling
  13143. @norecompute  CHAR(12)= 'NO'      -- Optional 'NORECOMPUTE' text - if present, then statistics 
  13144.                 -- will not be updated automatically
  13145. AS
  13146. /*
  13147.     NOTE: This sp will update statistics for *all* columns of all tables
  13148.     which the user has the privilege to update stats on (sysadmin, dbo, owner). 
  13149.     The following columns are not considered
  13150.     - first column of an index
  13151.     - column which already has statistics 
  13152.     - unelligible columns (Text and image columns consisting of ntext, text, or image data type, 
  13153.       bit, and computed columns)
  13154.     
  13155. */
  13156.  
  13157. declare @sysadmin int
  13158.     ,@dbname sysname
  13159.  
  13160. -- remember if the user is sysadmin 
  13161.  
  13162.       SELECT @sysadmin = is_srvrolemember('sysadmin'), @dbname = db_name()
  13163.  
  13164. -- create temporary table (column, index position)  
  13165. create table #colpostab
  13166. (    col_name  sysname, 
  13167.     col_pos      int,
  13168. )
  13169.  
  13170. set nocount on
  13171.  
  13172. DECLARE @exec_stmt nvarchar(540)
  13173. DECLARE @tablename sysname
  13174. DECLARE @columnname sysname
  13175. --DECLARE @shortcolumnname sysname
  13176. DECLARE @indexname sysname
  13177. DECLARE @uid smallint
  13178. DECLARE @indid smallint
  13179. DECLARE @position smallint
  13180. DECLARE @table_id  int
  13181. DECLARE @user_name sysname
  13182. DECLARE @numcols int   -- number of eligible columns found
  13183. DECLARE @msg nvarchar(386)
  13184. DECLARE @timestamp varchar(17)
  13185.  
  13186. DECLARE @tablename_header varchar(267)
  13187.         
  13188. DECLARE tnames_cursor INSENSITIVE CURSOR FOR SELECT name, id, uid FROM sysobjects WHERE type = 'U' and ((object_id('[#colpostab]') is NULL) OR (id <> object_id('[#colpostab]')))
  13189.  
  13190. SELECT @numcols = 0
  13191.  
  13192. OPEN tnames_cursor
  13193. FETCH NEXT FROM tnames_cursor INTO @tablename, @table_id, @uid
  13194. WHILE (@@fetch_status <> -1)
  13195. BEGIN
  13196.     IF ((@@fetch_status <> -2) AND ((@sysadmin = 1) OR (user_id() = @uid)))
  13197.     BEGIN
  13198.         -- these are all columns for which the statistics will be updated
  13199.         DECLARE cnames_cursor CURSOR FOR SELECT c.name   FROM syscolumns c, systypes t
  13200.             WHERE c.id = @table_id AND c.xtype = t.xusertype AND
  13201.                  (t.name NOT IN ('text', 'ntext', 'image', 'timestamp','bit'))
  13202.             AND ((c.colstat & 0x0004) <> 0x0004)  
  13203.             AND (c.length<=900)
  13204.             AND c.name NOT IN (SELECT col_name FROM #colpostab WHERE col_pos = 1)
  13205.             AND ((c.name IN (SELECT col_name FROM #colpostab)) OR (@indexonly <> 'indexonly'))
  13206.             
  13207.         -- populate temporary table of all (column, index position) tuples for this table  
  13208.  
  13209.         TRUNCATE TABLE #colpostab
  13210.  
  13211.         -- for each index on the table, loop though all columns and insert rows  
  13212.         -- OPEN CURSOR OVER INDEXES
  13213.         DECLARE ind_curs INSENSITIVE CURSOR FOR 
  13214.             SELECT indid, name FROM sysindexes
  13215.                 where id = @table_id and indid > 0 and indid < 255 order by indid
  13216.         
  13217.         OPEN ind_curs
  13218.         FETCH ind_curs into @indid , @indexname
  13219.  
  13220.         -- IF AN INDEX EXISTS
  13221.         
  13222.         WHILE @@fetch_status >= 0
  13223.         BEGIN
  13224.             -- Every index has at least one column at position 1
  13225.             INSERT INTO #colpostab VALUES (index_col(@tablename,@indid,1),1)
  13226.             -- now try position 2 and beyond....
  13227.             SELECT @columnname = index_col(@tablename, @indid, 2)
  13228.             SELECT @position = 2
  13229.             WHILE (@columnname is not null )
  13230.                 BEGIN
  13231.                     INSERT INTO #colpostab VALUES (@columnname,@position)
  13232.                     SELECT @position = @position +1
  13233.                     SELECT @columnname = index_col(@tablename, @indid, @position)
  13234.                 END
  13235.             -- Next Index
  13236.             FETCH ind_curs into @indid , @indexname
  13237.  
  13238.         END
  13239.         CLOSE ind_curs
  13240.         DEALLOCATE ind_curs
  13241.                         
  13242.         -- now go over all columns which are eligible for updating statistics 
  13243.         -- and are not first columns of any index
  13244.         -- optionaly we test if they are covered by some index (as non-leading)
  13245.  
  13246.         SELECT @user_name = user_name(@uid)
  13247.  
  13248.         OPEN cnames_cursor
  13249.  
  13250.         FETCH NEXT FROM cnames_cursor INTO @columnname
  13251.         IF @@fetch_status < 0
  13252.         BEGIN
  13253.             select @msg = @dbname +'.'+ @user_name +'.'+ @tablename
  13254.             raiserror(15013,-1,-1,@msg)
  13255.         END
  13256.         ELSE
  13257.         BEGIN
  13258.             select @msg = @dbname +'.'+ @user_name +'.'+ @tablename
  13259.             raiserror(15018, -1, -1, @msg)
  13260.         END
  13261.  
  13262.         WHILE @@fetch_status >= 0
  13263.         BEGIN                            
  13264.               SELECT @numcols = @numcols +1
  13265.              -- use the column name as the name for the statistics as well
  13266.              select @exec_stmt = 'CREATE STATISTICS ' +  quotename(@columnname, '[')  + ' ON ' +
  13267.          quotename( @user_name ,'[')+'.' + quotename( @tablename, '[')+'('+ quotename( @columnname, '[')+')'
  13268.             -- determining the correct suffix
  13269.             if ((@fullscan = 'FULLSCAN') AND (@norecompute = 'NORECOMPUTE'))
  13270.                 select @exec_stmt = @exec_stmt + ' WITH FULLSCAN, NORECOMPUTE'
  13271.             else if (@fullscan = 'FULLSCAN') select @exec_stmt = @exec_stmt + ' WITH FULLSCAN'
  13272.             else if (@norecompute = 'NORECOMPUTE') select @exec_stmt = @exec_stmt + ' WITH NORECOMPUTE'
  13273.             EXEC (@exec_stmt)
  13274.             --PRINT 'Statement='+@exec_stmt
  13275.             if (@@ERROR = 0)  -- otherwise the CREATE STATS will give a message
  13276.                  PRINT '     ' + @columnname
  13277.             FETCH NEXT FROM cnames_cursor INTO @columnname
  13278.         END
  13279.         CLOSE cnames_cursor
  13280.         DEALLOCATE cnames_cursor 
  13281.     END
  13282.     FETCH NEXT FROM tnames_cursor INTO @tablename, @table_id, @uid
  13283. END
  13284.  
  13285. PRINT ' '
  13286. raiserror(15020,-1,-1,@numcols)
  13287.  
  13288. DEALLOCATE tnames_cursor 
  13289.  
  13290. IF (object_id('[#colpostab]') is not null)
  13291.    begin
  13292.             drop table [#colpostab] 
  13293.    end
  13294.  
  13295. return(0) -- sp_createstats
  13296. go
  13297.  
  13298. ------------------------------- sp_cycle_errorlog -----------------------------------
  13299. raiserror(15339,-1,-1,'sp_cycle_errorlog')
  13300. go
  13301. create procedure sp_cycle_errorlog  --- 1997/06/24 
  13302. as
  13303. if suser_id() <> 1      -- Make sure that it is the SA executing this.
  13304.         begin
  13305.                 raiserror(15003,-1,-1, 'sysadmin')
  13306.                 return(1)
  13307.         end
  13308.  
  13309. dbcc errorlog
  13310. return (0)
  13311. go
  13312.  
  13313.  
  13314.  
  13315.  
  13316.  
  13317. -------------------------------- sp_helptrigger -----------------------------------
  13318.  
  13319. raiserror(15339,-1,-1,'sp_helptrigger')
  13320. go
  13321. create procedure sp_helptrigger  --- 1997/06/24 
  13322.     @tabname nvarchar(776),            /*    Table name        */
  13323.     @triggertype char(6) = NULL    /*    Trigger type    */
  13324. as
  13325.  
  13326. declare @objid int,        /* id of the object */
  13327.         @dbname sysname,
  13328.         @deltrig int,
  13329.         @instrig int,
  13330.         @updtrig int
  13331.  
  13332. -- Check to see that the object names are local to the current database.
  13333. select @dbname = parsename(@tabname,3) 
  13334.  
  13335. if @dbname is not null and @dbname <> db_name()
  13336. begin
  13337.         raiserror(15250,-1,-1)
  13338.         return (1)
  13339. end
  13340.  
  13341. select @objid =  id from sysobjects where id = object_id(@tabname)
  13342.     and type in ('S','U')
  13343.  
  13344. if @objid is null
  13345.     begin
  13346.         select @dbname = db_name()
  13347.         raiserror(15009,-1,-1,@tabname,@dbname)
  13348.         return(1)
  13349.     end
  13350.  
  13351. /*    Check that input type is UPDATE, INSERT, DELETE    */
  13352. if @triggertype  is not null and not UPPER(@triggertype ) in ('UPDATE', 'INSERT', 'DELETE')
  13353.       begin
  13354.          raiserror(15305,-1,-1)
  13355.          return(1)
  13356.       end
  13357.  
  13358. if @triggertype  is NULL
  13359.     select 
  13360.     trigger_name = name,
  13361.     trigger_owner = user_name(uid),
  13362.     isupdate = ObjectProperty( id, 'ExecIsUpdateTrigger'),
  13363.     isdelete = ObjectProperty( id, 'ExecIsDeleteTrigger'),
  13364.     isinsert = ObjectProperty( id, 'ExecIsInsertTrigger')
  13365.     from sysobjects
  13366.     where parent_obj = @objid and type = 'TR'
  13367. else
  13368. begin
  13369.     set @deltrig = case 
  13370.         when  upper(@triggertype ) = 'DELETE' then 0
  13371.         else -1 end
  13372.     set @instrig = case
  13373.         when  upper(@triggertype ) = 'INSERT' then 0
  13374.         else  -1 end
  13375.     set @updtrig = case 
  13376.         when  upper(@triggertype ) = 'UPDATE' then 0
  13377.         else -1 end
  13378.     select 
  13379.     trigger_name = name,
  13380.     trigger_owner = user_name(uid),
  13381.     isupdate = ObjectProperty( id, 'ExecIsUpdateTrigger'),
  13382.     isdelete = ObjectProperty( id, 'ExecIsDeleteTrigger'),
  13383.     isinsert = ObjectProperty( id, 'ExecIsInsertTrigger')
  13384.     from sysobjects
  13385.     where parent_obj = @objid and
  13386.     ObjectProperty( id, 'ExecIsDeleteTrigger') > @deltrig and 
  13387.     ObjectProperty( id, 'ExecIsInsertTrigger') > @instrig and 
  13388.     ObjectProperty( id, 'ExecIsUpdateTrigger') > @updtrig and
  13389.     type = 'TR'
  13390. end
  13391. return(0)  --sp_helptrigger
  13392. go
  13393.  
  13394. raiserror(15339,-1,-1,'sp_fixindex')
  13395. go
  13396. create procedure sp_fixindex
  13397.         @dbname        sysname,
  13398.         @tabname    sysname,                  /* system table name */
  13399.         @indid        int                        /* index id value    */
  13400. as
  13401.  
  13402.     declare @indexname sysname
  13403.     /*
  13404.     **    Description:    allow the SA to force a drop and then a
  13405.     **            create index on system catalogs.
  13406.     **
  13407.     **    Usage:        sp_fixindex  database, systemcatalog, ind_id
  13408.     **
  13409.     **    Note:        before using this procedure the database has to
  13410.     **            be in single user mode. The sp_dboption has to
  13411.     **            be used for user databases, and update of
  13412.     **            sysdatabases for master.
  13413.     **
  13414.     */
  13415.  
  13416.     /* Check that current db is db for processing*/
  13417.     if db_name() <> @dbname
  13418.         begin
  13419.             raiserror(15555,-1,-1, @dbname)
  13420.             return(1)
  13421.         end
  13422.  
  13423.     /*
  13424.     **    Make sure we are 'fixing' a system catalog.
  13425.     */
  13426.     if not exists (select name from sysobjects where name = @tabname and type = 'S')
  13427.         begin
  13428.             raiserror(15193,-1,-1)
  13429.             return (1)
  13430.         end
  13431.  
  13432.  
  13433.     /* Check database is in single user mode */
  13434.     if ((select status from master..sysdatabases where name = @dbname) &
  13435.        (select number from master..spt_values where name = 'single user' and  type = 'D') = 0) and
  13436.        (select value from master..syscurconfigs where config = 102) <> 1
  13437.         begin
  13438.             raiserror(15308,-1,-1, @dbname)
  13439.             return(1)
  13440.         end
  13441.  
  13442.     /*
  13443.     **    Make sure that we are doing this on somenthing that
  13444.     **    has indexes (or real tables).
  13445.     */
  13446.     if exists (select id from sysindexes where id = object_id(@tabname) and status & 8 <> 0)
  13447.         begin
  13448.             raiserror(15194,-1,-1)
  13449.             return (1)
  13450.         end
  13451.  
  13452.     /* Get the index name    */
  13453.     select @indexname = name from sysindexes where id = object_id(@tabname) and  indid = @indid
  13454.  
  13455.     if @indexname is null
  13456.         begin
  13457.             raiserror(15323,-1,-1, @tabname)
  13458.             return (1)        
  13459.         end
  13460.  
  13461.     if (object_id(@tabname) <= object_id ('sysallocations'))
  13462.         begin
  13463.             dbcc dbrepair(@dbname, repairindex, @tabname, @indid)
  13464.         end
  13465.     else
  13466.         begin
  13467.             dbcc dbreindex(@tabname, @indexname)
  13468.         end
  13469.  
  13470.     return (0)
  13471. go
  13472.  
  13473. /******************************************************************************
  13474. *************************  LOGIN-SECURITY (LOCAL)  ****************************
  13475. ******************************************************************************/
  13476. checkpoint
  13477. go
  13478. if object_id('sp_addlogin','P') IS NOT NULL
  13479.     drop procedure sp_addlogin
  13480. if object_id('sp_password','P') IS NOT NULL
  13481.     drop procedure sp_password
  13482. if object_id('sp_droplogin','P') IS NOT NULL
  13483.     drop procedure sp_droplogin
  13484. if object_id('sp_MSaddlogin_implicit_ntlogin','P') IS NOT NULL
  13485.     drop procedure sp_MSaddlogin_implicit_ntlogin
  13486. if object_id('sp_grantlogin','P') IS NOT NULL
  13487.     drop procedure sp_grantlogin
  13488. if object_id('xp_grantlogin','P') IS NOT NULL
  13489.     drop procedure xp_grantlogin
  13490. if object_id('sp_validatelogins','P') IS NOT NULL
  13491.     drop procedure sp_validatelogins
  13492. if object_id('sp_denylogin','P') IS NOT NULL
  13493.     drop procedure sp_denylogin
  13494. if object_id('sp_revokelogin','P') IS NOT NULL
  13495.     drop procedure sp_revokelogin
  13496. if object_id('xp_revokelogin','P') IS NOT NULL
  13497.     drop procedure xp_revokelogin
  13498. if object_id('sp_defaultdb','P') IS NOT NULL
  13499.     drop procedure sp_defaultdb
  13500. if object_id('sp_defaultlanguage','P') IS NOT NULL
  13501.     drop procedure sp_defaultlanguage
  13502. if object_id('sp_addsrvrolemember','P') IS NOT NULL
  13503.     drop procedure sp_addsrvrolemember
  13504. if object_id('sp_dropsrvrolemember','P') IS NOT NULL
  13505.     drop procedure sp_dropsrvrolemember
  13506. go
  13507.  
  13508. ------------------------------- sp_addlogin -----------------------------------
  13509.  
  13510. raiserror(15339,-1,-1,'sp_addlogin')
  13511. go
  13512. create procedure sp_addlogin
  13513.     @loginame        sysname
  13514.    ,@passwd         sysname = Null
  13515.    ,@defdb          sysname = 'master'      -- UNDONE: DEFAULT CONFIGURABLE???
  13516.    ,@deflanguage    sysname = Null
  13517.    ,@sid            varbinary(16) = Null
  13518.    ,@encryptopt        varchar(20) = Null
  13519. AS
  13520.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13521.     set nocount on
  13522.     Declare @ret    int    -- return value of sp call
  13523.  
  13524.     -- CHECK PERMISSIONS --
  13525.     IF (not is_srvrolemember('securityadmin') = 1)
  13526.     begin
  13527.        raiserror(15003,-1,-1, 'securityadmin')
  13528.        return (1)
  13529.     end
  13530.  
  13531.     -- DISALLOW USER TRANSACTION --
  13532.     set implicit_transactions off
  13533.     IF (@@trancount > 0)
  13534.     begin
  13535.         raiserror(15002,-1,-1,'sp_addlogin')
  13536.         return (1)
  13537.     end
  13538.  
  13539.     -- VALIDATE LOGIN NAME AS:
  13540.     --  (1) Valid SQL Name (SQL LOGIN)
  13541.     --  (2) No backslash (NT users only)
  13542.     --  (3) Not a reserved login name
  13543.     execute @ret = sp_validname @loginame
  13544.     if (@ret <> 0)
  13545.         return (1)
  13546.     if (charindex('\', @loginame) > 0)
  13547.     begin
  13548.         raiserror(15006,-1,-1,@loginame)
  13549.         return (1)
  13550.     end
  13551.  
  13552.     --Note: different case sa is allowed.
  13553.     if (@loginame = 'sa' or lower(@loginame) in ('public'))
  13554.     begin
  13555.         raiserror(15405, -1 ,-1, @loginame)
  13556.         return (1)
  13557.     end
  13558.  
  13559.     -- LOGIN NAME MUST NOT ALREADY EXIST --
  13560.     if exists(select * from master.dbo.syslogins where loginname = @loginame)
  13561.     begin
  13562.         raiserror(15025,-1,-1,@loginame)
  13563.         return (1)
  13564.     end
  13565.  
  13566.     -- VALIDATE DEFAULT DATABASE --
  13567.     IF db_id(@defdb) IS NULL
  13568.     begin
  13569.         raiserror(15010,-1,-1,@defdb)
  13570.         return (1)
  13571.     end
  13572.  
  13573.     -- VALIDATE DEFAULT LANGUAGE --
  13574.     IF (@deflanguage IS NOT Null)
  13575.     begin
  13576.         Execute @ret = sp_validlang @deflanguage
  13577.         IF (@ret <> 0)
  13578.             return (1)
  13579.     end
  13580.     ELSE
  13581.     begin
  13582.         select @deflanguage = name from master.dbo.syslanguages
  13583.         where langid = @@default_langid    --server default language
  13584.         
  13585.         if @deflanguage is null
  13586.             select @deflanguage = N'us_english'
  13587.     end
  13588.  
  13589.     -- VALIDATE SID IF GIVEN --
  13590.     if ((@sid IS NOT Null) and (datalength(@sid) <> 16))
  13591.     begin
  13592.         raiserror(15419,-1,-1)
  13593.          return (1)
  13594.     end
  13595.     else if @sid is null
  13596.         select @sid = newid()
  13597.     if (suser_sname(@sid) IS NOT Null)
  13598.     begin
  13599.         raiserror(15433,-1,-1)
  13600.          return (1)
  13601.     end
  13602.  
  13603.     -- VALIDATE AND USE ENCRYPTION OPTION --
  13604.     declare @xstatus smallint
  13605.     select @xstatus = 2    -- access
  13606.     if @encryptopt is null
  13607.         select @passwd = pwdencrypt(@passwd)
  13608.     else if @encryptopt = 'skip_encryption_old'
  13609.     begin
  13610.         select @xstatus = @xstatus | 0x800,    -- old-style encryption
  13611.             @passwd = convert(sysname, convert(varbinary(30), convert(varchar(30), @passwd)))
  13612.     end
  13613.     else if @encryptopt <> 'skip_encryption'
  13614.     begin
  13615.         raiserror(15600,-1,-1,'sp_addlogin')
  13616.         return 1
  13617.     end
  13618.  
  13619.     -- ATTEMPT THE INSERT OF THE NEW LOGIN --
  13620.     INSERT INTO master.dbo.sysxlogins VALUES
  13621.         (NULL, @sid, @xstatus, getdate(),
  13622.             getdate(), @loginame, convert(varbinary(256), @passwd),
  13623.             db_id(@defdb), @deflanguage)
  13624.  
  13625.     -- FINALIZATION: RETURN SUCCESS/FAILURE --
  13626.     if @@error <> 0
  13627.         return (1)
  13628.     raiserror(15298,-1,-1)
  13629.     return  (0)    -- sp_addlogin
  13630. go
  13631.  
  13632. ------------------------------- sp_password -----------------------------------
  13633.  
  13634. raiserror(15339,-1,-1,'sp_password')
  13635. go
  13636. create procedure sp_password
  13637.     @old sysname = NULL,        -- the old (current) password
  13638.     @new sysname,               -- the new password
  13639.     @loginame sysname = NULL    -- user to change password on
  13640. as
  13641.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13642.     set nocount on
  13643.     declare @self int
  13644.     select @self = CASE WHEN @loginame is null THEN 1 ELSE 0 END
  13645.  
  13646.     -- CHECK PERMISSIONS --
  13647.     IF (not is_srvrolemember('sysadmin') = 1)
  13648.         AND not @self = 1
  13649.     begin
  13650.        raiserror(15210,-1,-1)
  13651.        return (1)
  13652.     end
  13653.  
  13654.     -- DISALLOW USER TRANSACTION --
  13655.     set implicit_transactions off
  13656.     IF (@@trancount > 0)
  13657.     begin
  13658.         raiserror(15002,-1,-1,'sp_password')
  13659.         return (1)
  13660.     end
  13661.  
  13662.     -- RESOLVE LOGIN NAME (disallows nt names)
  13663.     if @loginame is null
  13664.         select @loginame = suser_sname()
  13665.     if not exists (select * from master.dbo.syslogins where
  13666.                     loginname = @loginame and isntname = 0)
  13667.     begin
  13668.         raiserror(15007,-1,-1,@loginame)
  13669.         return (1)
  13670.     end
  13671.  
  13672.     -- CHECK OLD PASSWORD IF NEEDED --
  13673.     if (@self = 1 or @old is not null)
  13674.         if not exists (select * from master.dbo.sysxlogins
  13675.                         where srvid IS NULL and
  13676.                               name = @loginame and
  13677.                               ( (@old is null and password is null) or
  13678.                               (pwdcompare(@old, password, (CASE WHEN xstatus&2048 = 2048 THEN 1 ELSE 0 END)) = 1) )   )
  13679.         begin
  13680.             raiserror(15211,-1,-1)
  13681.             return (1)
  13682.         end
  13683.  
  13684.     -- CHANGE THE PASSWORD --
  13685.     update master.dbo.sysxlogins 
  13686.     set password = convert(varbinary(256), pwdencrypt(@new)), xdate2 = getdate(), xstatus = xstatus & (~2048)
  13687.     where name = @loginame and srvid IS NULL
  13688.  
  13689.     -- FINALIZATION: RETURN SUCCESS/FAILURE --
  13690.     if @@error <> 0
  13691.         return (1)
  13692.     raiserror(15478,-1,-1)
  13693.     return  (0)    -- sp_password
  13694. go
  13695.  
  13696. checkpoint
  13697. go
  13698. ------------------------------- sp_droplogin ----------------------------------
  13699.  
  13700. raiserror(15339,-1,-1,'sp_droplogin')
  13701. go
  13702. create procedure sp_droplogin
  13703.     @loginame sysname
  13704. as
  13705.  
  13706. declare @exec_stmt nvarchar(890)
  13707.  
  13708.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13709.     set nocount on
  13710.     declare    @sid    varbinary(85)
  13711.  
  13712.     /*Create temp tables before any DML to ensure dynamic*/
  13713.     -- CREATE TEMPORARY TABLES FOR LATER USE --
  13714.        create table #db_list (dbname sysname not null, user_name sysname not null)
  13715.     create table #retval (job_count int not null)
  13716.  
  13717.     -- CHECK PERMISSIONS --
  13718.     IF (not is_srvrolemember('securityadmin') = 1)
  13719.     begin
  13720.        raiserror(15003,-1,-1, 'securityadmin')
  13721.        return (1)
  13722.     end
  13723.  
  13724.     -- DISALLOW USER TRANSACTION --
  13725.     set implicit_transactions off
  13726.     IF (@@trancount > 0)
  13727.     begin
  13728.         raiserror(15002,-1,-1,'sp_droplogin')
  13729.         return (1)
  13730.     end
  13731.  
  13732.     -- CANNOT CHANGE SA ROLES --
  13733.     if @loginame = 'sa'
  13734.     begin
  13735.         raiserror(15405, -1 ,-1, @loginame)
  13736.         return (1)
  13737.     end
  13738.  
  13739.     -- VALIDATE LOGIN NAME (SQL LOGIN) --
  13740.     select @sid = sid from master.dbo.syslogins
  13741.         where loginname = @loginame and isntname = 0
  13742.     if (@sid is null)
  13743.     begin
  13744.         raiserror(15007,10,-1,@loginame)
  13745.         return(1)
  13746.     end
  13747.  
  13748.     -- CHECK IF @sid IS CURRENTLY LOGGED IN (ignore cached remote connections) --
  13749.     if exists(select * from master.dbo.sysprocesses where sid = @sid and status != 'dormant')
  13750.     begin
  13751.         raiserror(15434, -1, -1, @loginame)
  13752.         return(1)
  13753.     end
  13754.  
  13755.     -- CHECK IF ANY DATABASES ARE OWNED BY LOGIN --
  13756.     if exists(select * from master.dbo.sysdatabases where sid = @sid)
  13757.     begin
  13758.         raiserror(15174, -1, -1, @loginame)
  13759.         select 'Databases owned by login:' = name
  13760.                 from master.dbo.sysdatabases where sid = @sid
  13761.         return(1)
  13762.     end
  13763.  
  13764.     -- COLLECT ALL INSTANCES OF USE OF THIS LOGIN IN SYSUSERS --
  13765.     declare @dbname        sysname
  13766.     declare db_name_cursor scroll cursor for select name from master.dbo.sysdatabases
  13767.     open db_name_cursor
  13768.     fetch db_name_cursor into @dbname
  13769.     while @@fetch_status >= 0
  13770.     begin
  13771.         if (has_dbaccess(@dbname) = 1)
  13772.         begin
  13773.             select @exec_stmt = 'use ' + quotename( @dbname , '[') + '
  13774.                    insert into #db_list (dbname, user_name)
  13775.                 select N'+ quotename( @dbname , '''')+', name from sysusers
  13776.                 where sid = suser_sid(N' + quotename( @loginame , '''') + ') '
  13777.             exec (@exec_stmt)
  13778.         end
  13779.         else
  13780.             raiserror(15622,-1,-1, @dbname)
  13781.  
  13782.         fetch db_name_cursor into @dbname
  13783.     end
  13784.     deallocate db_name_cursor
  13785.  
  13786.     -- ERROR IF LOGIN USED AS USER IN ANY DATABASE --
  13787.     if (select count(*) from #db_list) <> 0
  13788.     begin
  13789.         raiserror(15175,-1,-1,@loginame)
  13790.         select
  13791.             'Database name:' = dbname,
  13792.             'User name:' = user_name,
  13793.             'Mapping type:' = 'user'
  13794.         from #db_list
  13795.         return (1)
  13796.     end
  13797.  
  13798.     -- VERIFY NO JOBS IN MSDB OWNED BY THIS LOGIN --
  13799.     if db_id('msdb') is not null
  13800.         and object_id('msdb.dbo.sp_check_for_owned_jobs') is not null
  13801.     begin
  13802.         exec msdb.dbo.sp_check_for_owned_jobs @loginame, '#retval'
  13803.         if exists (select job_count from #retval where job_count > 0)
  13804.         begin
  13805.             declare @job_count int
  13806.             select @job_count = job_count from #retval
  13807.             raiserror(14248, -1, -1, @job_count)
  13808.             return (1)
  13809.         end
  13810.     end
  13811.  
  13812.     -- DELETE THIS LOGIN (ALSO DELETES REMOTE LOGINS MAPPED TO IT) --
  13813.     delete from master.dbo.sysxlogins where sid = @sid
  13814.  
  13815.     -- FINALIZATION: SUCCESS/FAILURE MESSAGE
  13816.     if @@rowcount > 0
  13817.     begin
  13818.         raiserror(15479,-1,-1)
  13819.         return (0)
  13820.     end
  13821.     else
  13822.     begin
  13823.         raiserror(15007,10,-1,@loginame)
  13824.         return (1)
  13825.     end     -- sp_droplogin
  13826. go
  13827.  
  13828. ----------------------- sp_MSaddlogin_implicit_ntlogin ------------------------
  13829.  
  13830. raiserror(15339,-1,-1,'sp_MSaddlogin_implicit_ntlogin')
  13831. go
  13832. ----------------------------------------
  13833. -- NOTE: FOR INTERNAL SECURITY USE ONLY!
  13834. --      DO NOT DOCUMENT OR USE!
  13835. ----------------------------------------
  13836. create procedure sp_MSaddlogin_implicit_ntlogin
  13837.     @loginame        sysname
  13838. AS
  13839.  
  13840. declare @default_lang sysname
  13841.  
  13842.     -- NO-OP IF LOGIN ALREADY EXISTS --
  13843.     -- if suser_sid(@loginame) is null
  13844.  
  13845.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  13846.     begin
  13847.  
  13848.         -- MUST BE NT NAME --
  13849.         if (charindex('\', @loginame) = 0)
  13850.             return (1)
  13851.  
  13852.         declare    @newsid    varbinary(85),
  13853.                 @status smallint
  13854.  
  13855.         -- OBTAIN NT SID FOR THIS LOGIN (SET STATUS BITS) --
  13856.         select @status = 4      -- ntlogin(4)
  13857.         select @newsid = get_sid('\U'+@loginame, NULL)        -- NT user
  13858.         if (@newsid IS Null)
  13859.         begin
  13860.             select @newsid = get_sid('\G'+@loginame, NULL)  -- NT group
  13861.             IF (@newsid IS Null)
  13862.                 return (1)
  13863.         end
  13864.         else
  13865.             select @status = @status | 8    -- NTUser
  13866.  
  13867.         select @default_lang = name from master.dbo.syslanguages
  13868.         where langid = @@default_langid     --server default language
  13869.  
  13870.         
  13871.         -- ADD IMPLICIT LOGIN ENTRY --
  13872.         INSERT into master.dbo.sysxlogins Values
  13873.             (NULL, @newsid, @status, getdate(), getdate(),
  13874.                 @loginame, NULL, 1, isnull(@default_lang, N'us_english'))
  13875.     end
  13876.  
  13877.     -- RETURN FAILURE/SUCCESS
  13878.     return @@error -- sp_MSaddlogin_implicit_ntlogin
  13879. go
  13880.  
  13881. ------------------------------- sp_grantlogin ---------------------------------
  13882.  
  13883. raiserror(15339,-1,-1,'sp_grantlogin')
  13884. go
  13885. create procedure sp_grantlogin
  13886.     @loginame        sysname
  13887. AS
  13888.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13889.     set nocount on
  13890.     declare @ret   int    -- return value of sp call
  13891.  
  13892.     -- CHECK PERMISSIONS --
  13893.     IF (not is_srvrolemember('securityadmin') = 1)
  13894.     begin
  13895.        raiserror(15003,-1,-1, 'securityadmin')
  13896.        return (1)
  13897.     end
  13898.  
  13899.     -- DISALLOW USER TRANSACTION --
  13900.     set implicit_transactions off
  13901.     IF (@@trancount > 0)
  13902.     begin
  13903.         raiserror(15002,-1,-1,'sp_grantlogin')
  13904.         return (1)
  13905.     end
  13906.  
  13907.     -- DISALLOW SQL LOGIN (IE. MUST BE 'DOMAIN\USER') --
  13908.     if (charindex('\', @loginame) = 0)
  13909.     begin
  13910.         raiserror(15407, -1, -1, @loginame)
  13911.         return (1)
  13912.     end
  13913.  
  13914.     -- ADD ROW FOR NT LOGIN IF NEEDED --
  13915.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  13916.     begin
  13917.         execute @ret = sp_MSaddlogin_implicit_ntlogin @loginame
  13918.         if (@ret <> 0)
  13919.         begin
  13920.             raiserror(15401,-1,-1 ,@loginame)
  13921.             return (1)
  13922.         end
  13923.     end
  13924.  
  13925.     -- UPDATE LOGIN BITS --
  13926.     update master.dbo.sysxlogins set xstatus = (xstatus & ~1) | 2, xdate2 = getdate()
  13927.         where name = @loginame and srvid IS NULL
  13928.  
  13929.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  13930.     if @@error <> 0
  13931.     begin
  13932.         raiserror(15480,-1,-1,@loginame)
  13933.         return (1)
  13934.     end
  13935.     else
  13936.     begin
  13937.         raiserror(15481,-1,-1,@loginame)
  13938.         return (0)
  13939.     end -- sp_grantlogin
  13940. go
  13941.  
  13942. ------------------------------- sp_validatelogins ---------------------------------
  13943.  
  13944. raiserror(15339,-1,-1,'sp_validatelogins')
  13945. go
  13946. create proc sp_validatelogins
  13947. AS
  13948.     -- Must be securityadmin (or sysadmin) to execute
  13949.     if is_srvrolemember('securityadmin') = 0 and is_srvrolemember('sysadmin') = 0
  13950.     begin
  13951.         raiserror(15003,-1,-1, 'securityadmin')
  13952.         return 1
  13953.     end
  13954.  
  13955.     -- Use get_sid() to determine if nt name is still valid (builtin is only available from system procs!)
  13956.     select 'SID' = sid, 'NT Login' = loginname from master.dbo.syslogins
  13957.         where isntname = 1 and get_sid(loginname, NULL) is null
  13958.     return 0 -- sp_validatelogins
  13959. go
  13960.  
  13961. -- FOR BACKWARD COMPATIBILTY ONLY --
  13962. raiserror(15339,-1,-1,'xp_grantlogin')
  13963. go
  13964. create procedure xp_grantlogin
  13965.     @loginame       sysname,
  13966.     @logintype      varchar(5) = Null       -- ignored unless 'admin'
  13967. AS
  13968.     set nocount on
  13969.  
  13970.     -- IF NAME NOT 'DOMAIN\USER', ADD DEFAULT DOMAIN --
  13971.     if (charindex('\', @loginame) = 0)
  13972.     begin
  13973.         declare @defdom varchar(25)
  13974.         exec master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
  13975.                 'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer',
  13976.                 'DefaultDomain', @defdom out
  13977.         select @loginame = @defdom + '\' + @loginame
  13978.     end
  13979.  
  13980.     Declare @ret   int     -- return value of sp call
  13981.     execute @ret = sp_grantlogin @loginame
  13982.     if (@ret = 0 and @logintype = 'admin')
  13983.         execute @ret = sp_addsrvrolemember @loginame, 'sysadmin'
  13984.     return (@ret)
  13985. go
  13986.  
  13987. checkpoint
  13988. go
  13989. ------------------------------- sp_denylogin ----------------------------------
  13990.  
  13991. raiserror(15339,-1,-1,'sp_denylogin')
  13992. go
  13993. create procedure sp_denylogin
  13994.     @loginame        sysname
  13995. AS
  13996.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13997.     set nocount on
  13998.     declare @ret   int    -- return value of sp call
  13999.  
  14000.     -- CHECK PERMISSIONS --
  14001.     IF (not is_srvrolemember('securityadmin') = 1)
  14002.     begin
  14003.        raiserror(15003,-1,-1, 'securityadmin')
  14004.        return (1)
  14005.     end
  14006.  
  14007.     -- DISALLOW USER TRANSACTION --
  14008.     set implicit_transactions off
  14009.     IF (@@trancount > 0)
  14010.     begin
  14011.         raiserror(15002,-1,-1,'sp_denylogin')
  14012.         return (1)
  14013.     end
  14014.  
  14015.     -- DISALLOW SQL LOGIN (IE. MUST BE 'DOMAIN\USER') --
  14016.     if (charindex('\', @loginame) = 0)
  14017.     begin
  14018.         raiserror(15407, -1, -1, @loginame)
  14019.         return (1)
  14020.     end
  14021.  
  14022.     -- ADD ROW FOR NT LOGIN IF NEEDED --
  14023.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  14024.     begin
  14025.         execute @ret = sp_MSaddlogin_implicit_ntlogin @loginame
  14026.         if (@ret <> 0)
  14027.         begin
  14028.             raiserror(15401,-1,-1 ,@loginame)
  14029.             return (1)
  14030.         end
  14031.     end
  14032.  
  14033.     -- UPDATE LOGIN BITS --
  14034.     update master.dbo.sysxlogins set xstatus = (xstatus & ~2) | 1, xdate2 = getdate()
  14035.         where name = @loginame and srvid IS NULL
  14036.  
  14037.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  14038.     if @@error <> 0
  14039.     begin
  14040.         raiserror(15482,-1,-1,@loginame)
  14041.         return (1)
  14042.     end
  14043.     else
  14044.     begin
  14045.         raiserror(15483,-1,-1,@loginame)
  14046.         return (0)
  14047.     end -- sp_denylogin
  14048. go
  14049.  
  14050. ------------------------------- sp_revokelogin --------------------------------
  14051.  
  14052. raiserror(15339,-1,-1,'sp_revokelogin')
  14053. go
  14054. create procedure sp_revokelogin
  14055.     @loginame        sysname
  14056. AS
  14057.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14058.     set nocount on
  14059.     declare    @sid    varbinary(85)
  14060.  
  14061.     -- CHECK PERMISSIONS --
  14062.     IF (not is_srvrolemember('securityadmin') = 1)
  14063.     begin
  14064.        raiserror(15003,-1,-1, 'securityadmin')
  14065.        return (1)
  14066.     end
  14067.  
  14068.     -- DISALLOW USER TRANSACTION --
  14069.     set implicit_transactions off
  14070.     IF (@@trancount > 0)
  14071.     begin
  14072.         raiserror(15002,-1,-1,'sp_revokelogin')
  14073.         return (1)
  14074.     end
  14075.  
  14076.     -- DISALLOW SQL LOGIN (IE. MUST BE 'DOMAIN\USER') --
  14077.     if (charindex('\', @loginame) = 0)
  14078.     begin
  14079.         raiserror(15407, -1, -1, @loginame)
  14080.         return (1)
  14081.     end
  14082.  
  14083.     -- REMOVE ROW IF EXISTS FOR LOGIN PROVIDED IT IS AN NT NAME --
  14084.     -- select @sid = suser_sid(@loginame)
  14085.     -- if @sid is not null
  14086.     if exists(select * from master.dbo.syslogins where loginname = @loginame and isntname = 1)
  14087.     begin
  14088.         select @sid = sid from master.dbo.syslogins where loginname = @loginame and isntname = 1
  14089.  
  14090.         -- For nt logins, skip sid foreign-key checks. --
  14091.         -- also deletes remote logins mapped to this user --
  14092.         delete from master.dbo.sysxlogins where sid = @sid
  14093.     end
  14094.     else
  14095.     begin
  14096.         -- CHECK IF THIS IS A VALID NT NAME BY GETTING ITS SID FROM NT
  14097.         declare    @newsid    varbinary(85)
  14098.         select @newsid = get_sid('\U'+@loginame, NULL)        -- NT user
  14099.         IF (@newsid IS Null)
  14100.         begin
  14101.             select @newsid = get_sid('\G'+@loginame, NULL)  -- NT group
  14102.             IF (@newsid IS Null)
  14103.             begin
  14104.                 raiserror(15401,-1,-1 ,@loginame)
  14105.                 return (1)
  14106.             end
  14107.         end
  14108.     end
  14109.  
  14110.  
  14111.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  14112.     if @@error <> 0
  14113.     begin
  14114.         raiserror(15484,-1,-1,@loginame)
  14115.         return (1)
  14116.     end
  14117.     else
  14118.     begin
  14119.         raiserror(15485,-1,-1,@loginame)
  14120.         return (0)
  14121.     end -- sp_revokelogin
  14122. go
  14123.  
  14124.  
  14125. -- FOR BACKWARD COMPATIBILTY ONLY --
  14126. raiserror(15339,-1,-1,'xp_revokelogin')
  14127. go
  14128. create procedure xp_revokelogin
  14129.     @loginame       sysname
  14130. AS
  14131.     set nocount on
  14132.  
  14133.     -- IF NAME NOT 'DOMAIN\USER', ADD DEFAULT DOMAIN --
  14134.     if (charindex('\', @loginame) = 0)
  14135.     begin
  14136.         declare @defdom varchar(25)
  14137.         exec master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
  14138.                 'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer',
  14139.                 'DefaultDomain', @defdom out
  14140.         select @loginame = @defdom + '\' + @loginame
  14141.     end
  14142.  
  14143.     Declare @ret   int     -- return value of sp call
  14144.     execute @ret = sp_revokelogin @loginame
  14145.     return (@ret)
  14146. go
  14147.  
  14148. ------------------------------- sp_defaultdb ----------------------------------
  14149.  
  14150. raiserror(15339,-1,-1,'sp_defaultdb')
  14151. go
  14152. create procedure sp_defaultdb
  14153.     @loginame   sysname,    -- login name
  14154.     @defdb      sysname     -- default db
  14155. as
  14156.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14157.     set nocount on
  14158.     declare @ret   int    -- return value of sp call
  14159.  
  14160.     -- CHECK PERMISSIONS --
  14161.     IF (not is_srvrolemember('securityadmin') = 1)
  14162.         AND not @loginame = suser_sname()
  14163.     begin
  14164.         raiserror(15132,-1,-1)
  14165.         return (1)
  14166.     end
  14167.  
  14168.     -- DISALLOW USER TRANSACTION --
  14169.     set implicit_transactions off
  14170.     IF (@@trancount > 0)
  14171.     begin
  14172.         raiserror(15002,-1,-1,'sp_defaultdb')
  14173.         return (1)
  14174.     end
  14175.  
  14176.  
  14177.     -- VALIDATE DATABASE NAME --
  14178.     if db_id(@defdb) IS NULL
  14179.     begin
  14180.         raiserror(15010,-1,-1,@defdb)
  14181.         return (1)
  14182.     end
  14183.  
  14184.     -- ADD ROW FOR NT LOGIN IF NEEDED --
  14185.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  14186.     begin
  14187.         execute @ret = sp_MSaddlogin_implicit_ntlogin @loginame
  14188.         if (@ret <> 0)
  14189.         begin
  14190.             raiserror(15007,-1,-1,@loginame)
  14191.             return (1)
  14192.         end
  14193.     end
  14194.  
  14195.     -- CHANGE DEFAULT DATABASE --
  14196.     update master.dbo.sysxlogins set dbid = db_id(@defdb), xdate2 = getdate()
  14197.         where name = @loginame and srvid IS NULL
  14198.  
  14199.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  14200.     IF (@@error <> 0)
  14201.         return (1)
  14202.     raiserror(15486,-1,-1)
  14203.     return (0) -- sp_defaultdb
  14204. go
  14205.  
  14206. checkpoint
  14207. go
  14208. ---------------------------- sp_defaultlanguage -------------------------------
  14209.  
  14210. raiserror(15339,-1,-1,'sp_defaultlanguage')
  14211. go
  14212. create procedure sp_defaultlanguage
  14213.     @loginame sysname,            -- login name
  14214.     @language sysname = NULL    -- default language
  14215. as
  14216.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14217.     set nocount on
  14218.     declare @ret   int     -- return value of sp call
  14219.  
  14220.     -- CHECK PERMISSIONS --
  14221.     IF (not is_srvrolemember('securityadmin') = 1)
  14222.         AND not @loginame = suser_sname()
  14223.     begin
  14224.         raiserror(15096,-1,-1,@loginame,@loginame)
  14225.         return (1)
  14226.     end
  14227.  
  14228.     -- DISALLOW USER TRANSACTION --
  14229.     set implicit_transactions off
  14230.     IF (@@trancount > 0)
  14231.     begin
  14232.         raiserror(15002,-1,-1,'sp_defaultlanguage')
  14233.         return (1)
  14234.     end
  14235.  
  14236.     -- VALIDATE LANGUAGE --
  14237.     IF (@language is not Null)
  14238.     begin
  14239.         Execute @ret = sp_validlang @language
  14240.         IF (@ret <> 0)
  14241.             return (1)
  14242.     end
  14243.     else
  14244.     begin
  14245.  
  14246.         select @language = name from master.dbo.syslanguages
  14247.         where langid = @@default_langid  --default language
  14248.  
  14249.         if @language is null
  14250.             select @language = N'us_english'
  14251.     end
  14252.  
  14253.     -- ADD ROW FOR NT LOGIN IF NEEDED --
  14254.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  14255.     begin
  14256.         execute @ret = sp_MSaddlogin_implicit_ntlogin @loginame
  14257.         if (@ret <> 0)
  14258.         begin
  14259.             raiserror(15007,-1,-1,@loginame)
  14260.             return (1)
  14261.         end
  14262.     end
  14263.  
  14264.     -- CHANGE DEFAULT LANGUAGE --
  14265.     update master.dbo.sysxlogins set language = @language, xdate2 = getdate()
  14266.         where name = @loginame and srvid IS NULL
  14267.  
  14268.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  14269.     if @@error <> 0
  14270.         return (1)
  14271.     raiserror(15487,-1,-1,@loginame,@language)
  14272.     return (0) -- sp_defaultlanguage
  14273. go
  14274.  
  14275. --------------------------- sp_addsrvrolemember -------------------------------
  14276.  
  14277. raiserror(15339,-1,-1,'sp_addsrvrolemember')
  14278. go
  14279. create procedure sp_addsrvrolemember
  14280.     @loginame sysname,            -- login name
  14281.     @rolename sysname = NULL    -- server role name
  14282. as
  14283.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14284.     set nocount on
  14285.     declare @ret        int,    -- return value of sp call
  14286.             @rolebit    smallint,
  14287.             @ismem      int
  14288.  
  14289.     -- DISALLOW USER TRANSACTION --
  14290.     set implicit_transactions off
  14291.     IF (@@trancount > 0)
  14292.     begin
  14293.         raiserror(15002,-1,-1,'sp_addsrvrolemember')
  14294.         return (1)
  14295.     end
  14296.  
  14297.     -- VALIDATE SERVER ROLE NAME, CHECKING PERMISSIONS --
  14298.     select @ismem = is_srvrolemember(@rolename)
  14299.     if @ismem is null
  14300.     begin
  14301.         raiserror(15402, -1, -1, @rolename)
  14302.         return (1)
  14303.     end
  14304.     if @ismem = 0
  14305.     begin
  14306.         raiserror(15403,-1,-1,@rolename)
  14307.         return (1)
  14308.     end
  14309.  
  14310.     -- CANNOT CHANGE SA ROLES --
  14311.     if @loginame = 'sa'
  14312.     begin
  14313.         raiserror(15405, -1 ,-1, @loginame)
  14314.         return (1)
  14315.     end
  14316.  
  14317.     -- OBTAIN THE BIT FOR THIS ROLE --
  14318.     select @rolebit = CASE @rolename
  14319.             WHEN 'sysadmin'         THEN 16
  14320.             WHEN 'securityadmin'    THEN 32
  14321.             WHEN 'serveradmin'      THEN 64
  14322.             WHEN 'setupadmin'       THEN 128
  14323.             WHEN 'processadmin'     THEN 256
  14324.             WHEN 'diskadmin'        THEN 512
  14325.             WHEN 'dbcreator'        THEN 1024
  14326.             ELSE NULL END
  14327.  
  14328.     -- ADD ROW FOR NT LOGIN IF NEEDED --
  14329.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  14330.     begin
  14331.         execute @ret = sp_MSaddlogin_implicit_ntlogin @loginame
  14332.         if (@ret <> 0)
  14333.         begin
  14334.             raiserror(15007,-1,-1,@loginame)
  14335.             return (1)
  14336.         end
  14337.     end
  14338.  
  14339.     -- UPDATE ROLE MEMBERSHIP --
  14340.     update master.dbo.sysxlogins set xstatus = xstatus | @rolebit, xdate2 = getdate()
  14341.         where name = @loginame and srvid IS NULL
  14342.  
  14343.     raiserror(15488,-1,-1,@loginame,@rolename)
  14344.  
  14345.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  14346.     return (@@error) -- sp_addsrvrolemember
  14347. go
  14348.  
  14349. checkpoint
  14350. go
  14351. --------------------------- sp_dropsrvrolemember ------------------------------
  14352.  
  14353. raiserror(15339,-1,-1,'sp_dropsrvrolemember')
  14354. go
  14355. create procedure sp_dropsrvrolemember
  14356.     @loginame sysname,            -- login name
  14357.     @rolename sysname = NULL    -- server role name
  14358. as
  14359.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14360.     set nocount on
  14361.     declare @ret        int,    -- return value of sp call
  14362.             @rolebit    smallint,
  14363.             @ismem      int
  14364.  
  14365.     -- DISALLOW USER TRANSACTION --
  14366.     set implicit_transactions off
  14367.     IF (@@trancount > 0)
  14368.     begin
  14369.         raiserror(15002,-1,-1,'sp_dropsrvrolemember')
  14370.         return (1)
  14371.     end
  14372.  
  14373.     -- VALIDATE SERVER ROLE NAME, CHECKING PERMISSIONS --
  14374.     select @ismem = is_srvrolemember(@rolename)
  14375.     if @ismem is null
  14376.     begin
  14377.         raiserror(15402, -1, -1, @rolename)
  14378.         return (1)
  14379.     end
  14380.     if @ismem = 0
  14381.     begin
  14382.         raiserror(15403,-1,-1,@rolename)
  14383.         return (1)
  14384.     end
  14385.  
  14386.     -- CANNOT CHANGE SA ROLES --
  14387.     if @loginame = 'sa'
  14388.     begin
  14389.         raiserror(15405, -1 ,-1, @loginame)
  14390.         return (1)
  14391.     end
  14392.  
  14393.     -- OBTAIN THE BIT FOR THIS ROLE --
  14394.     select @rolebit = CASE @rolename
  14395.             WHEN 'sysadmin'         THEN 16
  14396.             WHEN 'securityadmin'    THEN 32
  14397.             WHEN 'serveradmin'      THEN 64
  14398.             WHEN 'setupadmin'       THEN 128
  14399.             WHEN 'processadmin'     THEN 256
  14400.             WHEN 'diskadmin'        THEN 512
  14401.             WHEN 'dbcreator'        THEN 1024
  14402.             ELSE NULL END
  14403.  
  14404.     -- ERROR IF USER DOESNT EXIST --
  14405.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  14406.     begin
  14407.         raiserror(15007,-1,-1,@loginame)
  14408.         return (1)
  14409.     end
  14410.  
  14411.     -- UPDATE ROLE MEMBERSHIP --
  14412.     update master.dbo.sysxlogins set xstatus = xstatus & ~@rolebit, xdate2 = getdate()
  14413.         where name = @loginame and srvid IS NULL
  14414.  
  14415.     raiserror(15489,-1,-1,@loginame,@rolename)
  14416.  
  14417.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  14418.     return (@@error) -- sp_dropsrvrolemember
  14419. go
  14420.  
  14421. -- GRANT PUBLIC ACCESS (SP'S DO INTERNAL PERMISSIONS CHECKS) --
  14422. grant execute on sp_addlogin to public
  14423. grant execute on sp_password to public
  14424. grant execute on sp_droplogin to public
  14425. grant execute on sp_grantlogin to public
  14426. grant execute on sp_validatelogins to public
  14427. grant execute on xp_grantlogin to public
  14428. grant execute on sp_denylogin to public
  14429. grant execute on sp_revokelogin to public
  14430. grant execute on xp_revokelogin to public
  14431. grant execute on sp_defaultdb to public
  14432. grant execute on sp_defaultlanguage to public
  14433. grant execute on sp_addsrvrolemember to public
  14434. grant execute on sp_dropsrvrolemember to public
  14435. go
  14436. /**************************  END LOGIN-SECURITY ******************************/
  14437.  
  14438.  
  14439. /******************************************************************************
  14440. ************************  DATABASE-ACCESS-SECURITY  ***************************
  14441. ******************************************************************************/
  14442. checkpoint
  14443. go
  14444. if object_id('sp_MSadduser_implicit_ntlogin','P') IS NOT NULL
  14445.     drop procedure sp_MSadduser_implicit_ntlogin
  14446. if object_id('sp_MScheck_uid_owns_anything','P') IS NOT NULL
  14447.     drop procedure sp_MScheck_uid_owns_anything
  14448. if object_id('sp_grantdbaccess','P') IS NOT NULL
  14449.     drop procedure sp_grantdbaccess
  14450. if object_id('sp_revokedbaccess','P') IS NOT NULL
  14451.     drop procedure sp_revokedbaccess
  14452. if object_id('sp_adduser','P') IS NOT NULL
  14453.     drop procedure sp_adduser
  14454. if object_id('sp_dropuser','P') IS NOT NULL
  14455.     drop procedure sp_dropuser
  14456. if object_id('sp_addalias','P') IS NOT NULL
  14457.     drop procedure sp_addalias
  14458. if object_id('sp_dropalias','P') IS NOT NULL
  14459.     drop procedure sp_dropalias
  14460. if object_id('sp_addrole','P') IS NOT NULL
  14461.     drop procedure sp_addrole
  14462. if object_id('sp_droprole','P') IS NOT NULL
  14463.     drop procedure sp_droprole
  14464. if object_id('sp_addgroup','P') IS NOT NULL
  14465.     drop procedure sp_addgroup
  14466. if object_id('sp_dropgroup','P') IS NOT NULL
  14467.     drop procedure sp_dropgroup
  14468. if object_id('sp_addapprole','P') IS NOT NULL
  14469.     drop procedure sp_addapprole
  14470. if object_id('sp_approlepassword','P') IS NOT NULL
  14471.     drop procedure sp_approlepassword
  14472. if object_id('sp_setapprole','P') IS NOT NULL
  14473.     drop procedure sp_setapprole
  14474. if object_id('sp_dropapprole','P') IS NOT NULL
  14475.     drop procedure sp_dropapprole
  14476. if object_id('sp_addrolemember','P') IS NOT NULL
  14477.     drop procedure sp_addrolemember
  14478. if object_id('sp_droprolemember','P') IS NOT NULL
  14479.     drop procedure sp_droprolemember
  14480. if object_id('sp_changegroup','P') IS NOT NULL
  14481.     drop procedure sp_changegroup
  14482. if object_id('sp_change_users_login','P') IS NOT NULL
  14483.     drop procedure sp_change_users_login
  14484. if object_id('sp_changedbowner','P') IS NOT NULL
  14485.     drop procedure sp_changedbowner
  14486. if object_id('sp_check_removable_sysusers','P') IS NOT NULL
  14487.     drop procedure sp_check_removable_sysusers
  14488. if object_id('sp_changeobjectowner', 'P') IS NOT NULL
  14489.     drop procedure sp_changeobjectowner
  14490. go
  14491.  
  14492. ----------------------- sp_MSadduser_implicit_ntlogin -------------------------
  14493.  
  14494. raiserror(15339,-1,-1,'sp_MSadduser_implicit_ntlogin')
  14495. go
  14496. ----------------------------------------
  14497. -- NOTE: FOR INTERNAL SECURITY USE ONLY!
  14498. --      DO NOT DOCUMENT OR USE!
  14499. ----------------------------------------
  14500. create procedure sp_MSadduser_implicit_ntlogin
  14501.     @ntname         sysname
  14502. AS
  14503.     SET NOCOUNT ON -- required so internal calls don't send done packets
  14504.  
  14505.     -- NO-OP IF LOGIN ALREADY EXISTS --
  14506.     if user_id(@ntname) is null
  14507.     begin
  14508.  
  14509.         -- MUST BE NT NAME --
  14510.         if (charindex('\', @ntname) = 0)
  14511.             return (1)
  14512.  
  14513.         declare    @newsid    varbinary(85),
  14514.                 @status smallint,
  14515.                 @uid    smallint
  14516.  
  14517.         -- OBTAIN NT SID FOR THIS USER (SET STATUS BITS) --
  14518.         select @status = 4      -- ntlogin(4)
  14519.         select @newsid = get_sid('\U'+@ntname, NULL)        -- NT user
  14520.         if (@newsid is Null)
  14521.         begin
  14522.             select @newsid = get_sid('\G'+@ntname, NULL)    -- NT group
  14523.             IF (@newsid IS Null)
  14524.                 return (1)
  14525.         end
  14526.         else
  14527.             select @status = @status | 8    -- NTUser
  14528.  
  14529.         -- FAIL IF SID ALREADY IN SYSUSERS --
  14530.         if exists (select sid from sysusers where sid = @newsid)
  14531.             return (1)
  14532.  
  14533.         -- OBTAIN NEW UID (RESERVE 1-4) --
  14534.         if user_name(5) IS NULL
  14535.             select @uid = 5
  14536.         else
  14537.             select @uid = min(uid)+1 from sysusers
  14538.                 where uid >= 5 and uid < (16384 - 1)    -- stay in users range
  14539.                     and user_name(uid+1) is null        -- uid not in use
  14540.         if @uid is null
  14541.         begin
  14542.             raiserror(15065,-1,-1)
  14543.             return (1)
  14544.         end
  14545.  
  14546.         -- ADD IMPLICIT SYSUSERS ENTRY --
  14547.         insert into sysusers values
  14548.             (@uid, @status, @ntname, @newsid, 0x00, getdate(), getdate(), 0, NULL)
  14549.  
  14550.         -- INVALIDATE UID CACHE FOR THIS DB --
  14551.         grant all to null
  14552.     end
  14553.  
  14554.     -- RETURN FAILURE/SUCCESS --
  14555.     return @@error -- sp_MSadduser_implicit_ntlogin
  14556. go
  14557.  
  14558. ------------------------ sp_MScheck_uid_owns_anything -------------------------
  14559.  
  14560. raiserror(15339,-1,-1,'sp_MScheck_uid_owns_anything')
  14561. go
  14562. ----------------------------------------
  14563. -- NOTE: FOR INTERNAL SECURITY USE ONLY!
  14564. --      DO NOT DOCUMENT OR USE!
  14565. ----------------------------------------
  14566. create procedure sp_MScheck_uid_owns_anything
  14567.     @uid            smallint        -- uid to for which to check ownership
  14568. as
  14569.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14570.     set nocount on
  14571.     declare @isowner    int
  14572.     select @isowner = 0
  14573.  
  14574.     -- CHECK IF USER OWNS ANY OBJECTS --
  14575.     select @isowner = 0
  14576.     if exists (select uid from sysobjects where uid = @uid)
  14577.     begin
  14578.         raiserror(15183,-1,-1)
  14579.         select name, type from sysobjects where uid = @uid
  14580.         select @isowner = 1
  14581.     end
  14582.  
  14583.     -- CHECK IF USER OWNS ANY TYPES --
  14584.     if exists (select uid from systypes where uid = @uid)
  14585.     begin
  14586.         raiserror(15184,-1,-1)
  14587.         select user_type = name, physical_type = type_name(xtype)
  14588.                     from systypes where uid = @uid
  14589.         select @isowner = 1
  14590.     end
  14591.  
  14592.     -- CHECK IF USER GRANTED ANY PERMISSIONS --
  14593.     if exists (select grantor from syspermissions where grantor = @uid)
  14594.     begin
  14595.         raiserror(15284,-1,-1)
  14596.         select 'Grantee'=user_name(grantee) ,'Object'=object_name(id)
  14597.                     from syspermissions where grantor = @uid
  14598.         select @isowner = 1
  14599.     end
  14600.  
  14601.     -- CHECK IF USER OWNS ANY ROLES --
  14602.     if exists (select altuid from sysusers where altuid = @uid
  14603.                 and (issqlrole = 1 or isapprole = 1))
  14604.     begin
  14605.         raiserror(15421,-1,-1)
  14606.         select 'Role Name' = name,
  14607.                'Type' = CASE WHEN issqlrole=1 THEN 'SQL Role'
  14608.                              ELSE 'App Role' END
  14609.             from sysusers where altuid = @uid and (issqlrole = 1 or isapprole = 1)
  14610.         select @isowner = 1
  14611.     end
  14612.  
  14613.     return @isowner    -- sp_MScheck_uid_owns_anything
  14614. go
  14615.  
  14616. ------------------------------ sp_grantdbaccess -------------------------------
  14617.  
  14618. raiserror(15339,-1,-1,'sp_grantdbaccess')
  14619. go
  14620. create procedure sp_grantdbaccess
  14621.     @loginame       sysname,
  14622.     @name_in_db     sysname = NULL OUT
  14623. as
  14624.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14625.     set nocount on
  14626.     declare @ret        int,    -- return value of sp call
  14627.             @uid        smallint,
  14628.             @sid        varbinary(85),
  14629.             @status     smallint
  14630.  
  14631.     -- CHECK PERMISSIONS --
  14632.     if (not is_member('db_accessadmin') = 1) and
  14633.        (not is_member('db_owner') = 1)
  14634.     begin
  14635.         raiserror(15000,-1,-1)
  14636.         return (1)
  14637.     end
  14638.  
  14639.     -- DISALLOW USER TRANSACTION --
  14640.     set implicit_transactions off
  14641.     IF (@@trancount > 0)
  14642.     begin
  14643.         raiserror(15002,-1,-1,'sp_grantdbaccess')
  14644.         return (1)
  14645.     end
  14646.  
  14647.     -- VALIDATE NAME-IN-DB --
  14648.     if @name_in_db is null
  14649.         select @name_in_db = @loginame
  14650.     if @name_in_db <> @loginame
  14651.     begin
  14652.         exec @ret = sp_validname @name_in_db
  14653.         if @ret <> 0
  14654.             return(1)
  14655.         if (charindex('\', @name_in_db) > 0)
  14656.         begin
  14657.             raiserror(15006,-1,-1,@name_in_db)
  14658.             return (1)
  14659.         end
  14660.     end
  14661.  
  14662.     -- CHECK FOR SPECIAL USER GUEST --
  14663.     if @name_in_db = 'guest'
  14664.     begin
  14665.         -- ERROR IF NOT USER, OR ALREADY ADDED --
  14666.         if @loginame <> 'guest'
  14667.         begin
  14668.             raiserror(15062,-1,-1)
  14669.             return(1)
  14670.         end
  14671.         if exists (select * from sysusers where hasdbaccess = 1 and name = 'guest')
  14672.         begin
  14673.             raiserror(15023,-1,-1,'guest')
  14674.             return (1)
  14675.         end
  14676.  
  14677.         -- ENABLE USER GUEST --
  14678.         update sysusers set status = (status & ~1) | 2, updatedate = getdate()
  14679.                     where name = 'guest'
  14680.         return (0)
  14681.     end
  14682.  
  14683.     -- PREVENT USE OF CERTAIN LOGINS --
  14684.     if @loginame = 'sa'
  14685.     begin
  14686.         raiserror(15405, -1, -1, @loginame)
  14687.         return (1)
  14688.     end
  14689.  
  14690.     -- VALIDATE LOGIN NAME (OBTAIN SID) --
  14691.     select @status = case when (charindex('\', @loginame) <> 0) then 4 else 0 end
  14692.     if @status = 0
  14693.         select @sid = sid from master.dbo.syslogins         -- sql user
  14694.             where isntname = 0 and loginname = @loginame
  14695.     if @sid is null
  14696.     begin
  14697.         -- NT GROUPS REQUIRE DOMAIN NAME --
  14698.         if @status = 4
  14699.             select @sid = get_sid('\G'+@loginame, NULL)     -- nt group
  14700.         if @sid is null
  14701.         begin
  14702.             select @sid = get_sid('\U'+@loginame, NULL)     -- nt user
  14703.             if @sid is not null
  14704.                 select @status = 12
  14705.         end
  14706.     end
  14707.     if @sid is null
  14708.     begin
  14709.         if @status = 0
  14710.             raiserror(15007,-1,-1,@loginame)
  14711.         else
  14712.             raiserror(15401,-1,-1,@loginame)
  14713.         return (1)
  14714.     end
  14715.  
  14716.     -- CHECK IF LOGIN ALREADY IN DATABASE --
  14717.     if exists (select sid from sysusers where sid = @sid)
  14718.     begin
  14719.         -- ERROR IF LOGIN IS ALREADY ALIASED --
  14720.         if exists (select sid from sysusers where sid = @sid and isaliased = 1)
  14721.         begin
  14722.             raiserror(15022,-1,-1)
  14723.             return (1)
  14724.         end
  14725.  
  14726.         -- ERROR IF ALREADY EXISTS UNDER DIFFERENT NAME --
  14727.         if (not user_sid(user_id(@name_in_db)) = @sid)
  14728.         begin
  14729.             raiserror(15063,-1,-1)
  14730.             return (1)
  14731.         end
  14732.  
  14733.         -- ERROR IF LOGIN ALREADY HAS ACCESS --
  14734.         if exists (select sid from sysusers where sid = @sid and hasdbaccess = 1)
  14735.         begin
  14736.             if @status = 4
  14737.                 raiserror(15024,-1,-1,@name_in_db)
  14738.             else
  14739.                 raiserror(15023,-1,-1,@name_in_db)
  14740.             return (1)
  14741.         end
  14742.  
  14743.         -- GIVE DATABASE ACCESS TO THIS LOGIN --
  14744.         update sysusers set status = (status & ~1) | 2, updatedate = getdate()
  14745.                     where sid = @sid
  14746.         return @@error
  14747.     end
  14748.  
  14749.     if user_id(@name_in_db) is not null
  14750.     begin
  14751.         -- SYSUSERS NAME ALREADY EXISTS --
  14752.         if @status = 4
  14753.             raiserror(15024,-1,-1,@name_in_db)
  14754.         else
  14755.             raiserror(15023,-1,-1,@name_in_db)
  14756.         return (1)
  14757.     end
  14758.  
  14759.     -- OBTAIN NEW UID (RESERVE 1-4) --
  14760.     if user_name(5) IS NULL
  14761.         select @uid = 5
  14762.     else
  14763.         select @uid = min(uid)+1 from sysusers
  14764.             where uid >= 5 and uid < (16384 - 1)    -- stay in users range
  14765.                 and user_name(uid+1) is null        -- uid not in use
  14766.     if @uid is null
  14767.     begin
  14768.         raiserror(15065,-1,-1)
  14769.         return (1)
  14770.     end
  14771.  
  14772.     -- INSERT SYSUSERS ROW --
  14773.     insert into sysusers select
  14774.         @uid, @status | 2, @name_in_db, @sid, 0x00, getdate(), getdate(), 0, NULL
  14775.  
  14776.     -- INVALIDATE CACHED PERMISSIONS --
  14777.     grant all to null
  14778.  
  14779.     -- PRINT SUCCESS --
  14780.     raiserror(15341,-1,-1, @loginame)
  14781.  
  14782.     -- RETURN SUCCESS STATUS --
  14783.     return @@error -- sp_grantdbaccess
  14784. go
  14785.  
  14786. -- FOR BACKWARD COMPATIBILTY ONLY --
  14787. raiserror(15339,-1,-1,'sp_adduser')
  14788. go
  14789. create procedure sp_adduser
  14790.     @loginame       sysname,        -- user's login name in syslogins
  14791.     @name_in_db     sysname = NULL, -- user's name to add to current db
  14792.     @grpname        sysname = NULL  -- role to which user should be added.
  14793. as
  14794.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14795.     set nocount on
  14796.     declare @ret        int
  14797.  
  14798.     -- LIMIT TO SQL/NT USERS IN SYSLOGINS (BCKWRD COMPAT ONLY!)
  14799.     if not exists (select * from master.dbo.syslogins where loginname = @loginame
  14800.             and (isntuser = 1 or isntname = 0))
  14801.         and @loginame <> 'guest'
  14802.     begin
  14803.         raiserror(15007,-1,-1,@loginame)
  14804.         return (1)
  14805.     end
  14806.  
  14807.     -- VALIDATE THE ROLENAME --
  14808.     if @grpname is not null and
  14809.        not exists (select * from sysusers where name = @grpname and issqlrole = 1)
  14810.     begin
  14811.         raiserror(15014,-1,-1,@grpname)
  14812.         return (1)
  14813.     end
  14814.     -- In Hydra only the user dbo can do this --
  14815.     if (not is_member('dbo') = 1)
  14816.     begin
  14817.         raiserror(15000,-1,-1)
  14818.         return (1)
  14819.     end
  14820.  
  14821.     -- ADD THE USER TO THE DATABASE --
  14822.     execute @ret = sp_grantdbaccess @loginame, @name_in_db OUT
  14823.     if (@ret <> 0)
  14824.         return (1)
  14825.  
  14826.     -- ADD USER TO ROLE IF GIVEN. NOP FOR 'public' --
  14827.     if (@grpname is not null) and (@grpname <> 'public')
  14828.     begin
  14829.         execute @ret = sp_addrolemember @grpname, @name_in_db
  14830.         if @ret <> 0
  14831.         begin
  14832.             -- ROLL BACK THE ABOVE sp_grantdbaccess --
  14833.             if @name_in_db = 'guest'
  14834.                 update sysusers set status = status & ~2, updatedate = getdate()
  14835.                             where name = 'guest'
  14836.             else
  14837.                 delete from sysusers where name = @name_in_db
  14838.             return (1)
  14839.         end
  14840.     end
  14841.  
  14842.     -- RETURN SUCCESS --
  14843.     return (0) -- sp_adduser
  14844. go
  14845.  
  14846. checkpoint
  14847. go
  14848.  
  14849. ----------------------------- sp_revokedbaccess -------------------------------
  14850.  
  14851. raiserror(15339,-1,-1,'sp_revokedbaccess')
  14852. go
  14853. create procedure sp_revokedbaccess
  14854.     @name_in_db     sysname
  14855. as
  14856.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14857.     set nocount on
  14858.     declare @uid        smallint,
  14859.             @ret        int
  14860.  
  14861.     -- CHECK PERMISSIONS --
  14862.     if (not is_member('db_accessadmin') = 1) and
  14863.        (not is_member('db_owner') = 1)
  14864.     begin
  14865.         raiserror(15000,-1,-1)
  14866.         return (1)
  14867.     end
  14868.  
  14869.     -- DISALLOW USER TRANSACTION --
  14870.     set implicit_transactions off
  14871.     IF (@@trancount > 0)
  14872.     begin
  14873.         raiserror(15002,-1,-1,'sp_revokedbaccess')
  14874.         return (1)
  14875.     end
  14876.  
  14877.     -- CHECK IF SYSUSER EXISTS --
  14878.     select @uid = uid from sysusers where name = @name_in_db
  14879.             and (issqluser = 1 or isntname = 1)         -- is droppable entity
  14880.             and (name <> 'guest' or hasdbaccess = 1)    -- special case guest
  14881.     if @uid is null
  14882.     begin
  14883.         raiserror(15008,-1,-1,@name_in_db)
  14884.         return (1)
  14885.     end
  14886.  
  14887.     -- CANNOT DROP DBO/INFORMATION_SCHEMA/public --
  14888.     if @name_in_db in ('dbo','public','INFORMATION_SCHEMA')
  14889.     begin
  14890.         raiserror(15181,-1,-1)
  14891.         return (1)
  14892.     end
  14893.  
  14894.     -- CANNOT DROP GUEST IN MASTER/TEMPDB --
  14895.     if lower(@name_in_db) = 'guest' and db_id() in (1, 2)
  14896.     begin
  14897.         raiserror(15182,-1,-1)
  14898.         return(1)
  14899.     end
  14900.  
  14901.     -- CHECK IF USER OWNS ANYTHING --
  14902.     execute @ret = sp_MScheck_uid_owns_anything @uid
  14903.     if @ret <> 0
  14904.         return (1)
  14905.  
  14906.     -- REMOVE SYSPERMISSIONS ROWS AND DEPENDENT ALIASES --
  14907.     delete from syspermissions where grantee = @uid
  14908.     if exists (select altuid from sysusers where altuid = @uid and isaliased = 1)
  14909.     begin
  14910.         delete from sysusers where altuid = @uid and isaliased = 1
  14911.            raiserror(15490,-1,-1)
  14912.     end
  14913.  
  14914.     -- DROP USER: SPECIAL HANDLING FOR GUEST (REMOVE HASDBACCESS) --
  14915.     if lower(@name_in_db) = 'guest'
  14916.         update sysusers set status = status & ~2, updatedate = getdate() 
  14917.             where uid = user_id('guest')
  14918.     else
  14919.         delete from sysusers where uid = @uid
  14920.  
  14921.     -- RETURN SUCCESS/FAILURE --
  14922.     if @@error <> 0
  14923.         return (1)
  14924.  
  14925.     -- INVALIDATE CACHED PERMISSIONS --
  14926.     grant all to null
  14927.  
  14928.     raiserror(15491,-1,-1)
  14929.     return (0) -- sp_revokedbaccess
  14930. go
  14931.  
  14932. -- FOR BACKWARD COMPATIBILTY ONLY --
  14933. raiserror(15339,-1,-1,'sp_dropuser')
  14934. go
  14935. create procedure sp_dropuser
  14936.     @name_in_db     sysname     -- user name to drop
  14937. as
  14938.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14939.     set nocount on
  14940.     declare @ret    int
  14941.  
  14942.     -- LIMIT TO SQL/NT USERS (BCKWRD COMPAT ONLY!)
  14943.     if not exists (select * from sysusers where name = @name_in_db
  14944.                     and (isntuser = 1 or isntname = 0))
  14945.     begin
  14946.         raiserror(15008,-1,-1,@name_in_db)
  14947.         return (1)
  14948.     end
  14949.  
  14950.     -- DROP THE USER FROM THE DATABASE --
  14951.     execute @ret = sp_revokedbaccess @name_in_db
  14952.     if @ret <> 0
  14953.         return (1)
  14954.  
  14955.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  14956.     return (0) -- sp_dropuser
  14957. go
  14958.  
  14959. -------------------------------- sp_addalias ----------------------------------
  14960.  
  14961. raiserror(15339,-1,-1,'sp_addalias')
  14962. go
  14963. create procedure sp_addalias
  14964.     @loginame       sysname,    -- name of the pretender
  14965.     @name_in_db     sysname     -- user to whom to alias the login
  14966. as
  14967.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14968.     set nocount on
  14969.     declare @sid        varbinary(85),
  14970.             @targuid    smallint,
  14971.             @newuid     smallint,
  14972.             @status     smallint,
  14973.             @dbname     sysname
  14974.  
  14975.     -- CHECK PERMISSIONS --
  14976.     if (not is_member('db_accessadmin') = 1) and
  14977.        (not is_member('db_owner') = 1)
  14978.     begin
  14979.         raiserror(15000,-1,-1)
  14980.         return (1)
  14981.     end
  14982.  
  14983.     -- DISALLOW USER TRANSACTION --
  14984.     set implicit_transactions off
  14985.     IF (@@trancount > 0)
  14986.     begin
  14987.         raiserror(15002,-1,-1,'sp_addalias')
  14988.         return (1)
  14989.     end
  14990.  
  14991.     -- PREVENT USE OF CERTAIN LOGINS --
  14992.     if @loginame = 'sa'
  14993.     begin
  14994.         raiserror(15405, -1, -1, @loginame)
  14995.         return (1)
  14996.     end
  14997.  
  14998.     -- VALIDATE LOGIN NAME (OBTAIN SID) --
  14999.     select @status = CASE WHEN charindex('\', @loginame) > 0 THEN 12 ELSE 0 END
  15000.     if @status = 0
  15001.         select @sid = suser_sid(@loginame)          -- sql user
  15002.     -- retry sql user as nt with dflt domain
  15003.     if @sid is null
  15004.     begin
  15005.         select @sid = get_sid('\U'+@loginame, NULL) -- nt user
  15006.         if @sid is null
  15007.         begin
  15008.             if @status = 0
  15009.                 raiserror(15007,-1,-1,@loginame)
  15010.             else
  15011.                 raiserror(15401,-1,-1,@loginame)
  15012.             return (1)
  15013.         end
  15014.         select @status = 12
  15015.     end
  15016.  
  15017.     -- VALIDATE NAME-IN-DB (OBTAIN TARGET UID) --
  15018.     select @targuid = uid from sysusers where name = @name_in_db
  15019.                         and (issqluser = 1 or isntuser = 1)
  15020.     if @targuid is null
  15021.     begin
  15022.         raiserror(15008,-1,-1,@name_in_db)
  15023.         return (1)
  15024.     end
  15025.  
  15026.     -- ERROR IF LOGIN ALREADY IN DATABASE --
  15027.     if exists (select sid from sysusers where sid = @sid)
  15028.     begin
  15029.  
  15030.         -- ERROR IF ALREADY ALIASED --
  15031.         if exists (select sid from sysusers where sid = @sid and isaliased = 1)
  15032.         begin
  15033.             raiserror(15022,-1,-1)
  15034.             return (1)
  15035.         end
  15036.  
  15037.         -- ERROR: LOGIN ALREADY A USER --
  15038.         select @name_in_db = name, @dbname = db_name() from sysusers where sid = @sid
  15039.         raiserror(15278,-1,-1,@loginame,@name_in_db,@dbname)
  15040.         return (1)
  15041.     end
  15042.  
  15043.     -- ALTER NAME TO AVOID CONFLICTS IN NAME SPACE --
  15044.     select @loginame = '\' + @loginame
  15045.     if user_id(@loginame) is not null
  15046.     begin
  15047.         raiserror(15023,-1,-1,@loginame)
  15048.         return (1)
  15049.     end
  15050.  
  15051.     -- OBTAIN NEW UID (RESERVE 1-4) --
  15052.     if user_name(5) IS NULL
  15053.         select @newuid = 5
  15054.     else
  15055.         select @newuid = min(uid)+1 from sysusers
  15056.             where uid >= 5 and uid < (16384 - 1)    -- stay in users range
  15057.                 and user_name(uid+1) is null        -- uid not in use
  15058.     if @newuid is null
  15059.     begin
  15060.         raiserror(15065,-1,-1)
  15061.         return (1)
  15062.     end
  15063.  
  15064.     -- INSERT SYSUSERS ROW --
  15065.     insert into sysusers select
  15066.         @newuid, @status | 16, @loginame, @sid, 0x00,
  15067.                 getdate(), getdate(), @targuid, NULL
  15068.  
  15069.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15070.     if @@error <> 0
  15071.         return (1)
  15072.     raiserror(15340,-1,-1)
  15073.     return (0) -- sp_addalias
  15074. go
  15075.  
  15076. ------------------------------- sp_dropalias ----------------------------------
  15077.  
  15078. raiserror(15339,-1,-1,'sp_dropalias')
  15079. go
  15080. create procedure sp_dropalias
  15081.     @loginame   sysname     -- login who is currently aliased
  15082. as
  15083.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15084.     set nocount on
  15085.     declare @sid        varbinary(85)
  15086.  
  15087.     -- CHECK PERMISSIONS --
  15088.     if (not is_member('db_accessadmin') = 1) and
  15089.        (not is_member('db_owner') = 1)
  15090.     begin
  15091.         raiserror(15000,-1,-1)
  15092.         return (1)
  15093.     end
  15094.  
  15095.     -- DISALLOW USER TRANSACTION --
  15096.     set implicit_transactions off
  15097.     IF (@@trancount > 0)
  15098.     begin
  15099.         raiserror(15002,-1,-1,'sp_dropalias')
  15100.         return (1)
  15101.     end
  15102.  
  15103.    -- VALIDATE LOGIN NAME (OBTAIN SID) --
  15104.     if charindex('\', @loginame) = 0
  15105.         select @sid = suser_sid(@loginame)          -- sql user
  15106.     if @sid is null
  15107.     begin
  15108.         select @sid = get_sid('\U'+@loginame, NULL) -- nt user
  15109.         if @sid is null
  15110.         begin
  15111.             if charindex('\', @loginame) = 0
  15112.                 raiserror(15007,-1,-1,@loginame)
  15113.             else
  15114.                 raiserror(15401,-1,-1,@loginame)
  15115.             return (1)
  15116.         end
  15117.     end
  15118.  
  15119.     -- DELETE THE ALIAS (IF ANY) --
  15120.     delete from sysusers where sid = @sid and isaliased = 1
  15121.  
  15122.     -- ERROR IF NO ROW DELETED --
  15123.     if @@rowcount = 0
  15124.     begin
  15125.         raiserror(15134,-1,-1)
  15126.         return (1)
  15127.     end
  15128.  
  15129.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15130.     raiserror(15492,-1,-1)
  15131.     return (0) -- sp_dropalias
  15132. go
  15133.  
  15134. --------------------------------- sp_addrole ----------------------------------
  15135.  
  15136. raiserror(15339,-1,-1,'sp_addrole')
  15137. go
  15138. create procedure sp_addrole
  15139.     @rolename   sysname,        -- name of new role
  15140.     @ownername  sysname = 'dbo' -- name of owner of new role
  15141. as
  15142.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15143.     set nocount on
  15144.     declare @ret        int,    -- return value of sp call
  15145.             @uid        smallint,
  15146.             @owner      smallint
  15147.  
  15148.     -- CHECK PERMISSIONS --
  15149.     if (not is_member('db_securityadmin') = 1) and
  15150.        (not is_member('db_owner') = 1)
  15151.     begin
  15152.         raiserror(15000,-1,-1)
  15153.         return (1)
  15154.     end
  15155.  
  15156.     -- DISALLOW USER TRANSACTION --
  15157.     set implicit_transactions off
  15158.     if (@@trancount > 0)
  15159.     begin
  15160.         raiserror(15002,-1,-1,'sp_addrole')
  15161.         return (1)
  15162.     end
  15163.  
  15164.         -- RESOLVE OWNER NAME --
  15165.     select @owner = uid from sysusers where name = @ownername
  15166.                     and isaliased = 0 AND uid NOT IN (0,3,4) --public/INFO_SCHEMA/etc can't own role
  15167.     if @owner is null
  15168.     begin
  15169.         raiserror(15008,-1,-1,@ownername)
  15170.         return (1)
  15171.     end
  15172.  
  15173.     -- VALIDATE ROLE NAME --
  15174.     execute @ret = sp_validname @rolename
  15175.     if @ret <> 0
  15176.         return (1)
  15177.     if (charindex('\', @rolename) > 0)
  15178.     begin
  15179.         raiserror(15006,-1,-1,@rolename)
  15180.         return (1)
  15181.     end
  15182.  
  15183.     -- ERROR IF SYSUSERS NAME ALREADY EXISTS --
  15184.     if user_id(@rolename) is not null
  15185.     begin
  15186.         if exists (select name from sysusers where issqlrole = 1 and name = @rolename)
  15187.             raiserror(15363,-1,-1,@rolename)
  15188.         else
  15189.             raiserror(15023,-1,-1,@rolename)
  15190.  
  15191.         return (1)
  15192.     end
  15193.  
  15194.     -- OBTAIN NEW ROLE UID (RESERVE 16384-16399) --
  15195.     if user_name(16400) IS NULL
  15196.         select @uid = 16400
  15197.     else
  15198.         select @uid = min(uid)+1 from sysusers
  15199.             where uid >= 16400 and uid < (32767 - 1)    -- stay in role range
  15200.                 and user_name(uid+1) is null            -- uid not in use
  15201.     if @uid is null
  15202.     begin
  15203.         raiserror(15065,-1,-1)
  15204.         return (1)
  15205.     end
  15206.  
  15207.     -- INSERT THE ROW INTO SYSUSERS --
  15208.     insert into sysusers values
  15209.         (@uid, 0, @rolename, NULL, 0x00, getdate(), getdate(), @owner, NULL)
  15210.  
  15211.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15212.     if @@error <> 0
  15213.         return (1)
  15214.     raiserror(15424,-1,-1)
  15215.     return (0) -- sp_addrole
  15216. go
  15217.  
  15218. -- FOR BACKWARD COMPATIBLIITY --
  15219. raiserror(15339,-1,-1,'sp_addgroup')
  15220. go
  15221. create procedure sp_addgroup
  15222.     @grpname   sysname         -- name of new role
  15223. as
  15224.     declare @ret int
  15225.     execute @ret = sp_addrole @grpname
  15226.     return @ret
  15227. go
  15228.  
  15229. -------------------------------- sp_droprole ----------------------------------
  15230.  
  15231. raiserror(15339,-1,-1,'sp_droprole')
  15232. go
  15233. create procedure sp_droprole
  15234.     @rolename       sysname     -- role to be dropped
  15235. as
  15236.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15237.     set nocount on
  15238.     declare @uid        smallint,
  15239.             @owner      sysname,
  15240.             @ret        int
  15241.  
  15242.     -- DISALLOW USER TRANSACTION --
  15243.     set implicit_transactions off
  15244.     if (@@trancount > 0)
  15245.     begin
  15246.         raiserror(15002,-1,-1,'sp_droprole')
  15247.         return (1)
  15248.     end
  15249.  
  15250.     -- ROLE NAME (OBTAIN OWNER FOR PERMISSIONS) --
  15251.     select @uid = uid, @owner = user_name(altuid) from sysusers
  15252.             where name = @rolename and issqlrole = 1
  15253.  
  15254.     -- CHECK PERMISSIONS --
  15255.     if (not is_member('db_securityadmin') = 1) and
  15256.        (not is_member('db_owner') = 1) and
  15257.        (@owner is NULL or not is_member(@owner) = 1)
  15258.     begin
  15259.         raiserror(15000,-1,-1)
  15260.         return (1)
  15261.     end
  15262.  
  15263.     -- ERROR IF ROLE NOT FOUND --
  15264.     if @uid is null
  15265.     begin
  15266.         raiserror(15014,-1,-1,@rolename)
  15267.         return (1)
  15268.     end
  15269.  
  15270.     -- ERROR IF FIXED ROLE or PUBLIC ROLE--
  15271.     if @uid < 16400    or @uid = 0
  15272.     begin 
  15273.         raiserror(15142,-1,-1, @rolename)
  15274.         return (1)
  15275.     end
  15276.  
  15277.     -- ERROR IF ANYONE IS MEMBER OF ROLE (DISPLAYS MEMBERS) --
  15278.     if exists (select * from sysmembers where groupuid = @uid)
  15279.     begin
  15280.         raiserror(15144,-1,-1)
  15281.         select name = user_name(memberuid) from sysmembers where groupuid = @uid
  15282.         return (1)
  15283.     end
  15284.  
  15285.     -- CHECK IF ROLE OWNS ANYTHING --
  15286.     execute @ret = sp_MScheck_uid_owns_anything @uid
  15287.     if @ret <> 0
  15288.         return (1)
  15289.  
  15290.     -- DROP SYSUSERS AND PROTECTION ENTRIES --
  15291.     delete from syspermissions where grantee = @uid
  15292.     delete from sysusers where uid = @uid
  15293.  
  15294.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15295.     if @@error <> 0
  15296.         return (1)
  15297.     raiserror(15493,-1,-1)
  15298.     return (0) -- sp_droprole
  15299. go
  15300.  
  15301.  
  15302. -- FOR BACKWARD COMPATIBLIITY --
  15303. raiserror(15339,-1,-1,'sp_dropgroup')
  15304. go
  15305. create procedure sp_dropgroup
  15306.     @rolename   sysname         -- name of role to drop
  15307. as
  15308.     declare @ret int
  15309.     execute @ret = sp_droprole @rolename
  15310.     return @ret
  15311. go
  15312.  
  15313.  
  15314. checkpoint
  15315. go
  15316.  
  15317. ------------------------------- sp_addapprole ---------------------------------
  15318.  
  15319. raiserror(15339,-1,-1,'sp_addapprole')
  15320. go
  15321. create procedure sp_addapprole
  15322.     @rolename   sysname,        -- name of new app role
  15323.     @password   sysname         -- password for app role
  15324. as
  15325.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15326.     set nocount on
  15327.     declare @ret        int,    -- return value of sp call
  15328.             @uid        smallint
  15329.  
  15330.     -- CHECK FOR NULL PASSWORD
  15331.     if (@password is null)
  15332.     begin
  15333.         raiserror(15034,-1,-1)
  15334.         return (1)
  15335.     end
  15336.  
  15337.     -- CHECK PERMISSIONS --
  15338.     if (not is_member('db_securityadmin') = 1) and
  15339.        (not is_member('db_owner') = 1)
  15340.     begin
  15341.         raiserror(15000,-1,-1)
  15342.         return (1)
  15343.     end
  15344.  
  15345.     -- DISALLOW USER TRANSACTION --
  15346.     set implicit_transactions off
  15347.     if (@@trancount > 0)
  15348.     begin
  15349.         raiserror(15002,-1,-1,'sp_addapprole')
  15350.         return (1)
  15351.     end
  15352.  
  15353.     -- VALIDATE APPROLE NAME --
  15354.     execute @ret = sp_validname @rolename
  15355.     if @ret <> 0
  15356.         return (1)
  15357.     if (charindex('\', @rolename) > 0)
  15358.     begin
  15359.         raiserror(15006,-1,-1,@rolename)
  15360.         return (1)
  15361.     end
  15362.  
  15363.     -- ERROR IF SYSUSERS NAME ALREADY EXISTS --
  15364.     if user_id(@rolename) is not null
  15365.     begin
  15366.         raiserror(15363,-1,-1,@rolename)
  15367.         return (1)
  15368.     end
  15369.  
  15370.     -- OBTAIN NEW APPROLE UID (RESERVE 1-4) --
  15371.     if user_name(5) IS NULL
  15372.         select @uid = 5
  15373.     else
  15374.         select @uid = min(uid)+1 from sysusers
  15375.             where uid >= 5 and uid < (16384 - 1)    -- stay in users range
  15376.                 and user_name(uid+1) is null        -- uid not in use
  15377.     if @uid is null
  15378.     begin
  15379.         raiserror(15065,-1,-1)
  15380.         return (1)
  15381.     end
  15382.  
  15383.     -- INSERT THE ROW INTO SYSUSERS --
  15384.     insert into sysusers values
  15385.         (@uid, 32, @rolename, NULL, 0x00, getdate(),
  15386.                     getdate(), 1, convert(varbinary(256), pwdencrypt(@password)))
  15387.  
  15388.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15389.     if @@error <> 0
  15390.         return (1)
  15391.     raiserror(15425,-1,-1)
  15392.     return (0) -- sp_addapprole
  15393. go
  15394.  
  15395.  
  15396. ----------------------- sp_approlepassword -------------------------------------------
  15397.  
  15398. raiserror(15339,-1,-1,'sp_approlepassword')
  15399. go
  15400. CREATE PROCEDURE sp_approlepassword
  15401.     @rolename        sysname,            -- name of app role
  15402.     @newpwd            sysname                -- new password
  15403. AS
  15404.     declare @roluid        smallint
  15405.  
  15406.     -- CHECK FOR NULL PASSWORD
  15407.     if (@newpwd is null)
  15408.     begin
  15409.         raiserror(15034,-1,-1)
  15410.         return (1)
  15411.     end
  15412.  
  15413.     -- CHECK PERMISSIONS --
  15414.     if (not is_member('db_securityadmin') = 1) and
  15415.        (not is_member('db_owner') = 1)
  15416.     begin
  15417.         raiserror(15000,-1,-1)
  15418.         return (1)
  15419.     end
  15420.  
  15421.     -- DISALLOW USER TRANSACTION --
  15422.     set implicit_transactions off
  15423.     if (@@trancount > 0)
  15424.     begin
  15425.         raiserror(15002, -1, -1, 'sp_approlepassword')
  15426.         return (1)
  15427.     end
  15428.  
  15429.     -- ROLE UID (OBTAIN OWNER FOR PERMISSIONS) --
  15430.     -- @pwd will be encrypted.
  15431.     select @roluid = uid from sysusers
  15432.                 where name = @rolename and isapprole = 1
  15433.  
  15434.     -- ERROR IF APP ROLE NOT FOUND --
  15435.     if @roluid is null
  15436.     begin
  15437.         raiserror(15014, -1, -1, @rolename)
  15438.         return (1)
  15439.     end
  15440.  
  15441.     -- CHANGE PASSWORD --
  15442.     update sysusers set password = convert(varbinary(256), pwdencrypt(@newpwd)), updatedate = getdate()
  15443.             where uid = @roluid
  15444.     raiserror(15423,-1,-1,@rolename)
  15445.  
  15446.     return (0) -- sp_approlepassword
  15447. go
  15448.  
  15449.  
  15450. ------------------------------- sp_setapprole ---------------------------------
  15451.  
  15452. raiserror(15339,-1,-1,'sp_setapprole')
  15453. go
  15454. create procedure sp_setapprole
  15455.     @rolename   sysname,        -- name app role
  15456.     @password   sysname,        -- password for app role
  15457.     @encrypt    varchar(10)    = 'none'    -- Encryption style ('none' | 'odbc')
  15458. as
  15459.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15460.     set nocount on
  15461.  
  15462.     -- DISALLOW USER TRANSACTION --
  15463.     set implicit_transactions off
  15464.     if (@@trancount > 0)
  15465.     begin
  15466.         raiserror(15002,-1,-1,'sp_setapprole')
  15467.         return (1)
  15468.     end
  15469.  
  15470.     -- CHECK PARAMETER
  15471.     if (@rolename IS NULL)
  15472.     begin
  15473.         raiserror(15431,-1,-1)
  15474.         return (1)
  15475.     end
  15476.  
  15477.     -- VALIDATE ENCRYPTION
  15478.     declare @encrStyle int
  15479.     select @encrStyle = case lower(@encrypt) when 'none' then 0 when 'odbc' then 1 else null end
  15480.     if @encrStyle is null
  15481.     begin
  15482.         raiserror(15600,-1,-1,'sp_setapprole')
  15483.         return (1)
  15484.     end
  15485.  
  15486.     -- SP MUST BE CALLED AT ADHOC LEVEL --
  15487.     if (@@nestlevel > 1)
  15488.     begin
  15489.         raiserror(15422,-1,-1)
  15490.         return (1)
  15491.     end
  15492.  
  15493.     -- ACTIVATE APPROLE (THIS IS ONLY VALID FROM THIS SP!) --
  15494.     setuser @rolename, @password, @encrStyle
  15495.  
  15496.     -- RETURN SUCCESS/FAILURE --
  15497.     if (@@error <> 0)
  15498.         return (1)
  15499.  
  15500.     raiserror(15494,-1,-1,@rolename)
  15501.  
  15502.     return (0) -- sp_setapprole
  15503. go
  15504.  
  15505. ------------------------------ sp_dropapprole ---------------------------------
  15506.  
  15507. raiserror(15339,-1,-1,'sp_dropapprole')
  15508. go
  15509. create procedure sp_dropapprole
  15510.     @rolename       sysname     -- role to be dropped
  15511. as
  15512.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15513.     set nocount on
  15514.     declare @uid        smallint,
  15515.             @ret        int
  15516.  
  15517.     -- CHECK PERMISSIONS --
  15518.     if (not is_member('db_securityadmin') = 1) and
  15519.        (not is_member('db_owner') = 1)
  15520.     begin
  15521.         raiserror(15000,-1,-1)
  15522.         return (1)
  15523.     end
  15524.  
  15525.     -- DISALLOW USER TRANSACTION --
  15526.     set implicit_transactions off
  15527.     if (@@trancount > 0)
  15528.     begin
  15529.         raiserror(15002,-1,-1,'sp_dropapprole')
  15530.         return (1)
  15531.     end
  15532.  
  15533.     -- ERROR IF ROLE NOT FOUND --
  15534.     select @uid = uid from sysusers where name = @rolename and isapprole = 1
  15535.     if @uid is null
  15536.     begin
  15537.         raiserror(15014,-1,-1,@rolename)
  15538.         return (1)
  15539.     end
  15540.  
  15541.     -- CHECK IF ROLE OWNS ANYTHING --
  15542.     execute @ret = sp_MScheck_uid_owns_anything @uid
  15543.     if @ret <> 0
  15544.         return (1)
  15545.  
  15546.     -- DROP SYSUSERS AND PROTECTION ENTRIES --
  15547.     delete from syspermissions where grantee = @uid
  15548.     delete from sysusers where uid = @uid
  15549.  
  15550.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15551.     if @@error <> 0
  15552.         return (1)
  15553.     raiserror(15495,-1,-1)
  15554.     return (0) -- sp_dropapprole
  15555. go
  15556.  
  15557. ------------------------------ sp_addrolemember -------------------------------
  15558.  
  15559. raiserror(15339,-1,-1,'sp_addrolemember')
  15560. go
  15561. CREATE PROCEDURE sp_addrolemember
  15562.     @rolename       sysname,
  15563.     @membername     sysname
  15564. AS
  15565.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15566.     set nocount on
  15567.     declare @roluid     smallint,
  15568.             @owner      smallint,
  15569.             @memuid     smallint,
  15570.             @ret        int
  15571.     declare @ruidbyte   smallint,
  15572.             @ruidbit    smallint
  15573.     declare @proc        nvarchar(50)
  15574.  
  15575.     -- DISALLOW USER TRANSACTION --
  15576.     set implicit_transactions off
  15577.     if (@@trancount > 0)
  15578.     begin
  15579.         raiserror(15002,-1,-1,'sp_addrolemember')
  15580.         return (1)
  15581.     end
  15582.  
  15583.     -- ROLE NAME (OBTAIN OWNER FOR PERMISSIONS) --
  15584.     select @roluid = uid, @owner = altuid from sysusers
  15585.                 where name = @rolename and issqlrole = 1
  15586.  
  15587.     -- ERROR IF ROLE NOT FOUND OR PUBLIC --
  15588.     if @roluid is null or @rolename = 'public'
  15589.     begin
  15590.         raiserror(15014,-1,-1,@rolename)
  15591.         return (1)
  15592.     end
  15593.  
  15594.     -- CHECK PERMISSIONS --
  15595.     -- Only member of db_owner can add members to db-fixed roles --
  15596.     if (not is_member('db_owner') = 1) and
  15597.        (not (@roluid < 16400 and is_member('db_owner') = 1)) and
  15598.        (not (@roluid >= 16400 and is_member('db_securityadmin') = 1)) and
  15599.        (not (@roluid >= 16400 and is_member(user_name(@owner)) = 1))
  15600.     begin
  15601.         raiserror(15000,-1,-1)
  15602.         return (1)
  15603.     end
  15604.  
  15605.     -- CHECK MEMBER NAME (ATTEMPT ADDING IMPLICIT ROW FOR NT NAME) --
  15606.     select @memuid = uid from sysusers where name = @membername and isaliased = 0
  15607.     if @memuid is null
  15608.     begin
  15609.         execute @ret = sp_MSadduser_implicit_ntlogin @membername
  15610.         select @memuid = uid from sysusers where name = @membername and isaliased = 0
  15611.     end
  15612.     if @memuid is null
  15613.     begin
  15614.         raiserror(15410, -1, -1, @membername)
  15615.         return (1)
  15616.     end
  15617.  
  15618.     -- CANNOT CHANGE MEMBERSHIP OF FIXED ROLES OR DBO --
  15619.     if @membername in ('dbo','public') or (@memuid >= 16384 and @memuid < 16400)
  15620.     begin
  15621.         raiserror(15405, -1 ,-1, @membername)
  15622.         return (1)
  15623.     end
  15624.  
  15625.     -- CHECK FOR CIRCULAR MEMBERSHIPS --
  15626.     if is_userinrole(@rolename, @membername) = 1
  15627.     begin
  15628.         raiserror(15413, -1, -1)
  15629.         return (1)
  15630.     end
  15631.  
  15632.     -- SET ROLE BIT FOR THIS USER
  15633.     select @ruidbyte = ((@roluid - 16384) / 8) + 1
  15634.          , @ruidbit = power(2, @roluid & 7)
  15635.     update sysusers set roles = convert(varbinary(2048),
  15636.         stuff( convert(binary(2048), roles), @ruidbyte, 1, convert(binary(1),
  15637.             (@ruidbit) | substring(convert(binary(2048), roles), @ruidbyte, 1) ))),
  15638.             updatedate = getdate()
  15639.         where uid = @memuid
  15640.     -- END ROLE BIT MANIPULATION
  15641.  
  15642.     -- INVALIDATE CACHED PERMISSIONS (MEMBERSHIP CHANGES PERMISSIONS) --
  15643.     select @ret = @@error   -- save success state
  15644.     grant all to null
  15645.  
  15646.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15647.     if @@error <> 0 or @ret <> 0
  15648.         return (1)
  15649.  
  15650.     raiserror(15488,-1,-1,@membername,@rolename)
  15651.  
  15652.     return (0) -- sp_addrolemember
  15653. go
  15654.  
  15655. checkpoint
  15656. go
  15657.  
  15658. ----------------------------- sp_droprolemember -------------------------------
  15659.  
  15660. raiserror(15339,-1,-1,'sp_droprolemember')
  15661. go
  15662. CREATE PROCEDURE sp_droprolemember
  15663.     @rolename       sysname,
  15664.     @membername     sysname
  15665. AS
  15666.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15667.     set nocount on
  15668.     declare @roluid     smallint,
  15669.             @owner      smallint,
  15670.             @memuid     smallint,
  15671.             @ret        int
  15672.     declare @ruidbyte   smallint,
  15673.             @ruidbit    smallint
  15674.     declare @proc        nvarchar(50)
  15675.  
  15676.     -- DISALLOW USER TRANSACTION --
  15677.     set implicit_transactions off
  15678.     if (@@trancount > 0)
  15679.     begin
  15680.         raiserror(15002,-1,-1,'sp_droprolemember')
  15681.         return (1)
  15682.     end
  15683.         
  15684.         -- ROLE NAME (OBTAIN OWNER FOR PERMISSIONS) --
  15685.     select @roluid = uid, @owner = altuid from sysusers
  15686.                 where name = @rolename and issqlrole = 1
  15687.  
  15688.     -- ERROR IF ROLE NOT FOUND OR PUBLIC --
  15689.     if @roluid is null or @rolename = 'public'
  15690.     begin
  15691.         raiserror(15409,-1,-1,@rolename)
  15692.         return (1)
  15693.     end
  15694.  
  15695.     -- CHECK PERMISSIONS --
  15696.     -- Only member of db_owner can drop members from db-fixed roles --
  15697.     if (not is_member('db_owner') = 1) and
  15698.        (not (@roluid < 16400 and is_member('db_owner') = 1)) and
  15699.        (not (@roluid >= 16400 and is_member('db_securityadmin') = 1)) and
  15700.        (not (@roluid >= 16400 and is_member(user_name(@owner)) = 1))
  15701.     begin
  15702.         raiserror(15000,-1,-1)
  15703.         return (1)
  15704.     end
  15705.  
  15706.     -- ERROR IF MEMBER NAME NOT NULL AND NOT FOUND --
  15707.     select @memuid = uid from sysusers where name = @membername and isaliased = 0
  15708.     if @memuid is null
  15709.     begin
  15710.         raiserror(15410, -1, -1, @membername)
  15711.         return (1)
  15712.     end
  15713.  
  15714.     -- CANNOT CHANGE MEMBERSHIP OF FIXED ROLES OR DBO --
  15715.     if @membername in ('dbo','public') or (@memuid >= 16384 and @memuid < 16400)
  15716.     begin
  15717.         raiserror(15405, -1 ,-1, @membername)
  15718.         return (1)
  15719.     end
  15720.  
  15721.     -- CLEAR ROLE BIT FOR THIS USER
  15722.     select @ruidbyte = ((@roluid - 16384) / 8) + 1
  15723.          , @ruidbit = power(2, @roluid & 7)
  15724.     update sysusers set roles = convert(varbinary(2048),
  15725.         stuff( convert(binary(2048), roles), @ruidbyte, 1, convert(binary(1),
  15726.             (~@ruidbit) & substring(convert(binary(2048), roles), @ruidbyte, 1) ))),
  15727.             updatedate = getdate()
  15728.         where uid = @memuid
  15729.     -- END ROLE BIT MANIPULATION
  15730.  
  15731.     -- INVALIDATE CACHED PERMISSIONS (MEMBERSHIP CHANGES PERMISSIONS) --
  15732.     select @ret = @@error   -- save success state
  15733.     grant all to null
  15734.  
  15735.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15736.     if @@error <> 0 or @ret <> 0
  15737.         return (1)
  15738.  
  15739.     raiserror(15489,-1,-1,@membername,@rolename)
  15740.  
  15741.     return (0) -- sp_droprolemember
  15742. go
  15743.  
  15744. ------------------------------- sp_changegroup --------------------------------
  15745.  
  15746. raiserror(15339,-1,-1,'sp_changegroup')
  15747. go
  15748. create procedure sp_changegroup
  15749.     @grpname    sysname,    -- name of new role
  15750.     @username   sysname     -- user to switch
  15751. as
  15752.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15753.     set nocount on
  15754.     declare @uid        smallint,
  15755.             @ruid        smallint,
  15756.             @cnt        int,
  15757.             @ret        int,
  15758.             @oldgrp     sysname
  15759.  
  15760.      select @ruid = uid from sysusers
  15761.                 where name = @grpname and issqlrole = 1
  15762.  
  15763.     -- ERROR IF GROUP NOT FOUND --
  15764.     if @ruid is null
  15765.     begin
  15766.         raiserror(15014,-1,-1,@grpname)
  15767.         return (1)
  15768.     end
  15769.  
  15770.     -- LIMIT TO USERS WITH ACCESS (BACKWARD COMPAT ONLY!) --
  15771.     select @uid = uid from sysusers where name = @username
  15772.                 and (issqluser = 1 or isntuser = 1) and hasdbaccess = 1
  15773.     if @uid is null
  15774.     begin
  15775.         raiserror(15008,-1,-1,@username)
  15776.         return (1)
  15777.     end
  15778.  
  15779.     -- ONLY VALID IF USER IS MEMBER OF NO MORE THAN ONE GROUP --
  15780.     select @cnt = count(*) from sysmembers where memberuid = @uid
  15781.     if @cnt > 1
  15782.     begin
  15783.         raiserror(15415, -1, -1)
  15784.         return (1)
  15785.     end
  15786.  
  15787.     -- REMOVE MEMBERSHIP IF NEEDED --
  15788.     if (@cnt = 1)
  15789.     begin
  15790.         select @oldgrp = user_name(groupuid) from sysmembers where memberuid = @uid
  15791.         execute @ret = sp_droprolemember @oldgrp, @username
  15792.         if @ret <> 0
  15793.             return (1)
  15794.     end
  15795.  
  15796.     -- ADD MEMBERSHIP --
  15797.     if (@grpname <> 'public')
  15798.     begin
  15799.         execute @ret = sp_addrolemember @grpname, @username
  15800.         if @ret <> 0
  15801.             return (1)
  15802.     end
  15803.  
  15804.     -- FINALIZATION: RETURN SUCCESS --
  15805.     raiserror(15496,-1,-1)
  15806.  
  15807.     return (0) -- sp_changegroup
  15808. go
  15809.  
  15810. ---------------------------- sp_change_users_login ----------------------------
  15811.  
  15812. raiserror(15339,-1,-1,'sp_change_users_login')
  15813. go
  15814. CREATE PROCEDURE sp_change_users_login
  15815.     @Action               varchar(10)       -- REPORT / UPDATE_ONE / AUTO_FIX
  15816.    ,@UserNamePattern      sysname  = Null
  15817.    ,@LoginName            sysname  = Null
  15818. AS
  15819.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15820.     set nocount on
  15821.     declare @exec_stmt nvarchar(430)
  15822.  
  15823.     declare @ret            int,
  15824.             @FixMode        char(5),
  15825.             @cfixesupdate   int,        -- count of fixes by update
  15826.             @cfixesaddlogin int,        -- count of fixes by sp_addlogin
  15827.             @dbname         sysname,
  15828.             @loginsid       varbinary(85),
  15829.             @110name        sysname
  15830.  
  15831.     -- SET INITIAL VALUES --
  15832.     select  @dbname         = db_name(),
  15833.             @cfixesupdate   = 0,
  15834.             @cfixesaddlogin = 0
  15835.  
  15836.     -- ERROR IF IN USER TRANSACTION --
  15837.     if @@trancount > 0
  15838.     begin
  15839.         raiserror(15289,-1,-1)
  15840.         return (1)
  15841.     end
  15842.  
  15843.     -- INVALIDATE USE OF SPECIAL LOGIN/USER NAMES --
  15844.     if @LoginName = 'sa'
  15845.     begin
  15846.         raiserror(15287,-1,-1,@LoginName)
  15847.         return (1)
  15848.     end
  15849.     if lower(@UserNamePattern) in ('dbo','guest','INFORMATION_SCHEMA')
  15850.     begin
  15851.         raiserror(15287,-1,-1,@UserNamePattern)
  15852.         return (1)
  15853.     end
  15854.  
  15855.     -- HANDLE REPORT --
  15856.     if upper(@Action) = 'REPORT'
  15857.     begin
  15858.  
  15859.         -- VALIDATE PARAMS --
  15860.         if @UserNamePattern IS NOT Null or @LoginName IS NOT Null
  15861.         begin
  15862.             raiserror(15290,-1,-1,@Action,@UserNamePattern,@LoginName)
  15863.             return (1)
  15864.         end
  15865.  
  15866.         -- GENERATE REPORT --
  15867.         select UserName = name, UserSID = sid from sysusers
  15868.             where issqluser = 1 and (sid is not null and sid <> 0x0)
  15869.                     and suser_sname(sid) is null
  15870.             order by name
  15871.         return (0)
  15872.     end
  15873.  
  15874.     -- HANDLE UPDATE_ONE --
  15875.     if upper(@Action) = 'UPDATE_ONE'
  15876.     begin
  15877.  
  15878.         -- CHECK PERMISSIONS --
  15879.         if not is_member('db_owner') = 1
  15880.         begin
  15881.             raiserror(15288,-1,-1,'SA or DBO',@Action)
  15882.             return (1)
  15883.         end
  15884.  
  15885.         -- ERROR IF PARAMS NULL --
  15886.         if @UserNamePattern IS Null or @LoginName IS Null
  15887.         begin
  15888.             raiserror(15290,-1,-1,@Action,@UserNamePattern,@LoginName)
  15889.             return (1)
  15890.         end
  15891.  
  15892.         -- VALIDATE PARAMS --
  15893.         -- Can ONLY remap SQL Users to SQL Logins!  Should be no need
  15894.         --  for re-mapping NT logins, and if you try, you'll mess up
  15895.         --  the user status bits! (see samsmith)
  15896.         if not exists (select name from sysusers where
  15897.                 name = @UserNamePattern             -- match user name
  15898.             and issqluser = 1)                      -- must be sql user
  15899.         begin
  15900.             raiserror(15291,-1,-1,'User',@UserNamePattern)
  15901.             return (1)
  15902.         end
  15903.         select @loginsid = sid from master.dbo.syslogins where
  15904.                 loginname = @LoginName              -- match login name
  15905.             and isntname = 0                        -- cannot use nt logins
  15906.         if @loginsid is null
  15907.         begin
  15908.             raiserror(15291,-1,-1,'Login',@LoginName)
  15909.             return (1)
  15910.         end
  15911.  
  15912.         -- ERROR IF SID ALREADY IN USE IN DATABASE --
  15913.         if exists (select sid from sysusers where sid = @loginsid
  15914.                     and name <> @UserNamePattern)
  15915.         begin
  15916.             raiserror(15063,-1,-1)
  15917.             return (1)
  15918.         end
  15919.  
  15920.         -- CHANGE THE USERS LOGIN (SID) --
  15921.         update sysusers set sid = @loginsid, updatedate = getdate()
  15922.                 where name = @UserNamePattern and issqluser = 1
  15923.                 and sid <> @loginsid
  15924.  
  15925.         -- FINALIZATION: REPORT AND EXIT --
  15926.         if @@error <> 0 or @@rowcount <> 1
  15927.             raiserror(15295,-1,-1, 0)
  15928.         else
  15929.             raiserror(15295,-1,-1, 1)
  15930.         return (0)
  15931.     end
  15932.  
  15933.     -- ERROR IF NOT AUTO_FIX --
  15934.     if upper(@Action) <> 'AUTO_FIX'
  15935.     begin
  15936.         raiserror(15286,-1,-1,@Action)
  15937.         return (1)
  15938.     end
  15939.  
  15940.     -- HANDLE AUTO_FIX --
  15941.     -- CHECK PERMISSIONS --
  15942.     if not is_srvrolemember('sysadmin') = 1
  15943.     begin
  15944.         raiserror(15288,-1,-1,'SA or DBO',@Action)
  15945.         return (1)
  15946.     end
  15947.  
  15948.     -- VALIDATE PARAMS --
  15949.     if @UserNamePattern IS Null or @LoginName IS NOT Null
  15950.     begin
  15951.         raiserror(15290,-1,-1,@Action,@UserNamePattern,@LoginName)
  15952.         return (1)
  15953.     end
  15954.  
  15955.     -- LOOP THRU ORPHANED USERS --
  15956.     select @exec_stmt = 'DECLARE Cursor110_Users cursor for
  15957.             select name from sysusers
  15958.             where name = N' + quotename( @UserNamePattern , '''')+ '
  15959.                 and issqluser = 1 and suser_sname(sid) is null'
  15960.     EXECUTE (@exec_stmt)
  15961.     OPEN Cursor110_Users
  15962.  
  15963.     WHILE (110=110)
  15964.     begin
  15965.         FETCH next from Cursor110_Users into @110name
  15966.         if (@@fetch_status <> 0)
  15967.         begin
  15968.             DEALLOCATE Cursor110_Users
  15969.             BREAK
  15970.         end
  15971.  
  15972.         -- IS NAME ALREADY IN USE? --
  15973.         -- if suser_sid(@110name) is null
  15974.         if not exists(select * from master.dbo.syslogins where loginname = @110name)
  15975.         begin
  15976.  
  15977.             -- ADD LOGIN --
  15978.             execute @ret = sp_addlogin @110name, Null, @dbname
  15979.             if @ret <> 0 or suser_sid(@110name) is null
  15980.             begin
  15981.                 raiserror(15497,16,1,@110name)
  15982.                 deallocate Cursor110_Users
  15983.                 return (1)
  15984.             end
  15985.             select @FixMode = '1AddL'
  15986.             raiserror(15293,-1,-1,@110name)
  15987.         end
  15988.         ELSE
  15989.         begin
  15990.             Select @FixMode = '2UpdU'
  15991.             Raiserror(15292,-1,-1,@110name)
  15992.         end
  15993.  
  15994.         -- REPORT ERROR & CONTINUE IF DUPLICATE SID IN DB --
  15995.         select @loginsid = suser_sid(@110name)
  15996.         if user_sid(@loginsid) is not null
  15997.         begin
  15998.             raiserror(15331,-1,-1,@110name,@loginsid)
  15999.             CONTINUE
  16000.         end
  16001.  
  16002.         -- UPDATE SYSUSERS ROW --
  16003.         update sysusers set sid = @loginsid, updatedate = getdate() where name = @110name
  16004.         if @@error <> 0
  16005.         begin
  16006.             raiserror(15498,17,127)
  16007.             deallocate Cursor110_Users
  16008.             return (1)
  16009.         end
  16010.  
  16011.  
  16012.         if @FixMode = '1AddL'
  16013.             Select @cfixesaddlogin = @cfixesaddlogin + 1
  16014.         else
  16015.             Select @cfixesupdate = @cfixesupdate + 1
  16016.     end -- loop 110
  16017.  
  16018.     -- REPORT AND RETURN SUCCESS --
  16019.     raiserror(15295,-1,-1,@cfixesupdate)
  16020.     raiserror(15294,-1,-1,@cfixesaddlogin)
  16021.     return (0) -- sp_change_users_login
  16022. go
  16023.  
  16024. ------------------------------ sp_changedbowner -------------------------------
  16025.  
  16026. raiserror(15339,-1,-1,'sp_changedbowner')
  16027. go
  16028. create procedure sp_changedbowner
  16029.     @loginame       sysname,        -- login to become dbo
  16030.     @map            varchar(5) = NULL    -- True to map aliases, else drop
  16031. as
  16032.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  16033.     set nocount on
  16034.     declare @ret        int,
  16035.             @newsid     varbinary(85),
  16036.             @status     smallint
  16037.  
  16038.     -- CHECK PERMISSIONS (Note: All sysadmins are dbo) --
  16039.     if is_member('db_owner') = 0
  16040.     begin
  16041.         raiserror(15108,-1,-1)
  16042.         return(1)
  16043.     end
  16044.  
  16045.     -- CANT CHANGE OWNER OF MASTER/MODEL/TEMPDB --
  16046.     if db_name() in ('master', 'model', 'tempdb')
  16047.     begin
  16048.         raiserror(15109,-1,-1)
  16049.         return(1)
  16050.     end
  16051.  
  16052.     -- CHECK LOGIN NAME IS VALID (NT/SQL USER ONLY!) --
  16053.     select @newsid = sid, @status = 2 from master.dbo.syslogins
  16054.                     where loginname = @loginame and isntname = 0
  16055.     if @newsid is null
  16056.         select @status = 14, @newsid = get_sid('\U'+@loginame, NULL)
  16057.     if @newsid is null
  16058.     begin
  16059.         raiserror(15007,-1,-1,@loginame)
  16060.         return (1)
  16061.     end
  16062.  
  16063.     -- CHECK IF LOGIN ALREADY ALIASED IN DB --
  16064.     if exists (select sid from sysusers where isaliased = 1 and sid = @newsid)
  16065.     begin
  16066.         raiserror(15111,-1,-1)
  16067.         return (1)
  16068.     end
  16069.  
  16070.     -- CHECK IF LOGIN ALREADY KNOWN TO DATABASE --
  16071.     if exists (select sid from sysusers where sid = @newsid)
  16072.     begin
  16073.         raiserror(15110,-1,-1)
  16074.         return (1)
  16075.     end
  16076.  
  16077.     -- MAKE THE FOLLOWING REMOVE/REMAP/DELETES ATOMIC --
  16078.     begin transaction
  16079.  
  16080.     -- REMAP DBO TO NEW SID --
  16081.     update sysusers set sid = @newsid, status = @status, updatedate = getdate()
  16082.             where name = 'dbo'
  16083.  
  16084.     -- REMOVE OTHER DBO-ALIASES IF REMAPPING NOT REQUESTED --
  16085.     if lower(@map) <> 'true'
  16086.     begin
  16087.         delete from sysusers where isaliased = 1 and altuid = user_id('dbo')
  16088.         raiserror(15500,-1,-1)
  16089.     end
  16090.     else
  16091.         raiserror(15499,-1,-1)     -- nothing to do to <remap>
  16092.  
  16093.     -- REFLECT NEW OWNER IN SYSDATABASES --
  16094.     update master.dbo.sysdatabases set sid = @newsid where dbid = db_id()
  16095.     commit transaction
  16096.  
  16097.     -- CHECKPOINT DATABASE TO FORCE CHANGES TO IN-MEMORY STRUCTURE --
  16098.     checkpoint
  16099.     raiserror(15501,-1,-1)
  16100.     return (0) -- sp_changedbowner
  16101. go
  16102.  
  16103. ------------------------- sp_check_removable_sysusers -------------------------
  16104.  
  16105. raiserror(15339,-1,-1,'sp_check_removable_sysusers')
  16106. go
  16107. -----------------------------------------------------
  16108. -- NOTE: FOR INTERNAL USE ONLY (sp_certify_removable)
  16109. --      DO NOT DOCUMENT OR USE!
  16110. -----------------------------------------------------
  16111. create procedure sp_check_removable_sysusers
  16112.     @autofix    varchar(4)      -- true or other
  16113. as
  16114.     -- CHECK FOR DATABASE OWNED BY SQL USER --
  16115.     if exists (select name from sysusers where name = 'dbo' and issqluser = 1 and sid <> suser_sid('sa'))
  16116.     begin
  16117.         if @autofix <> 'auto'
  16118.         begin
  16119.             raiserror(15258,-1,-1)
  16120.             return(1)
  16121.         end
  16122.  
  16123.         -- MAKE SA THE DBO --
  16124.         raiserror(15502,-1,-1)
  16125.         update sysusers set sid = suser_sid('sa'), status = 2, updatedate = getdate()
  16126.                 where name = 'dbo'
  16127.     end
  16128.  
  16129.     -- CHECK FOR PERMISSIONS GRANTED TO or BY SQL USERS --
  16130.     if exists (select grantee from syspermissions where grantee in
  16131.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4))
  16132.     OR exists (select grantor from syspermissions where grantor in
  16133.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4))
  16134.     begin
  16135.         if @autofix = 'auto'
  16136.             PRINT 'CANNOT AUTO-AUTOFIX GRANT-WITH-GRANT CHAINS'
  16137.         raiserror(15053,-1,-1)
  16138.         return(1)
  16139.     end
  16140.  
  16141.     -- CHECK FOR OBJECTS OWNED BY SQL USERS --
  16142.     if exists (select uid from sysobjects where uid in
  16143.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4))
  16144.     begin
  16145.         if @autofix <> 'auto'
  16146.         begin
  16147.             raiserror(15053,-1,-1)
  16148.             return(1)
  16149.         end
  16150.  
  16151.         -- ASSIGN DBO AS OWNER OF OTHER OBJECTS (MAY FAIL WITH DUPL!) --
  16152.         raiserror(15503,-1,-1)
  16153.         update sysobjects set uid = 1 where uid in
  16154.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4)
  16155.         if @@error <> 0
  16156.             return (1)
  16157.     end
  16158.  
  16159.     -- CHECK FOR TYPES OWNED BY SQL USERS --
  16160.     if exists (select uid from systypes where uid in
  16161.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4))
  16162.     begin
  16163.         if @autofix <> 'auto'
  16164.         begin
  16165.             raiserror(15053,-1,-1)
  16166.             return(1)
  16167.         end
  16168.  
  16169.         -- ASSIGN DBO AS OWNER OF TYPES --
  16170.         raiserror(15503,-1,-1)
  16171.         update systypes set uid = 1 where uid in
  16172.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4)
  16173.     end
  16174.  
  16175.     -- CHECK FOR ROLES OWNED BY SQL USERS --
  16176.     if exists (select altuid from sysusers where (issqlrole = 1 or isapprole = 1) and
  16177.         altuid in (select uid from sysusers u where u.issqluser = 1 and u.uid > 4))
  16178.     begin
  16179.         if @autofix <> 'auto'
  16180.         begin
  16181.             raiserror(15053,-1,-1)
  16182.             return(1)
  16183.         end
  16184.  
  16185.         -- ASSIGN DBO AS OWNER OF TYPES --
  16186.         raiserror(15503,-1,-1)
  16187.         update sysusers set altuid = 1, updatedate = getdate()
  16188.             where (issqlrole = 1 or isapprole = 1) and
  16189.             altuid in (select uid from sysusers u where u.issqluser = 1 and u.uid > 4)
  16190.     end
  16191.  
  16192.     -- CHECK FOR SQL LOGINS AS USERS --
  16193.     if exists (select uid from sysusers where issqluser = 1 and uid > 4)
  16194.     begin
  16195.         if @autofix <> 'auto'
  16196.         begin
  16197.             raiserror(15254,-1,-1)
  16198.             return(1)
  16199.         end
  16200.  
  16201.         -- DELETE SQL USERS AND DEPENDENT ALIASES --
  16202.         raiserror(15504,-1,-1)
  16203.         delete from sysusers where issqluser = 1 and uid > 4
  16204.         delete from sysusers where isaliased = 1 and user_name(altuid) is null
  16205.     end
  16206.  
  16207.     -- CHECK FOR SQL LOGINS ALIASED --
  16208.     if exists (select uid from sysusers where isaliased = 1 and isntname = 0)
  16209.     begin
  16210.         if @autofix <> 'auto'
  16211.         begin
  16212.             raiserror(15254,-1,-1)
  16213.             return(1)
  16214.         end
  16215.  
  16216.         -- DELETE ALIASED SQL USERS --
  16217.         raiserror(15504,-1,-1)
  16218.         delete from sysusers where isaliased = 1 and isntname = 0
  16219.     end
  16220.  
  16221.     -- Success
  16222.     return 0
  16223. go
  16224.  
  16225. checkpoint
  16226. go
  16227.  
  16228. ---------------------------- sp_changeobjectowner -----------------------------
  16229.  
  16230. raiserror(15339,-1,-1,'sp_changeobjectowner')
  16231. go
  16232. create procedure sp_changeobjectowner
  16233.     @objname    nvarchar(517),        -- may be "[owner].[object]"
  16234.     @newowner    sysname                -- must be entry from sysusers
  16235. as
  16236.     Set nocount      on
  16237.     Set ansi_padding on
  16238.     declare    @objid        int,
  16239.             @newuid        smallint
  16240.  
  16241.     -- CHECK PERMISSIONS: Because changing owner changes both schema and
  16242.     --    permissions, the caller must be one of:
  16243.     -- (1) db_owner
  16244.     -- (2) db_ddladmin AND db_securityadmin
  16245.     if (is_member('db_owner') = 0) and
  16246.         (is_member('db_securityadmin') = 0 OR is_member('db_ddladmin') = 0)
  16247.     begin
  16248.         raiserror(15000,-1,-1)
  16249.         return (1)
  16250.     end
  16251.  
  16252.     -- RESOLVE OBJECT NAME (CANNOT BE A CHILD OBJECT: TRIGGER/CONSTRAINT) --
  16253.     select @objid = object_id(@objname, 'local')
  16254.     if (@objid is null) OR (select parent_obj from sysobjects where id = @objid) <> 0
  16255.     begin
  16256.         -- OBJECT NOT FOUND
  16257.         raiserror(15001,-1,-1,@objname)
  16258.         return 1
  16259.     end
  16260.  
  16261.     -- RESOLVE NEW OWNER NAME (ATTEMPT ADDING IMPLICIT ROW FOR NT NAME) --
  16262.     --  Disallow aliases, and public cannot own objects --
  16263.     select @newuid = uid from sysusers where name = @newowner
  16264.                             and isaliased = 0 and name <> 'public'
  16265.     if @newuid is null
  16266.     begin
  16267.         execute sp_MSadduser_implicit_ntlogin @newowner
  16268.         select @newuid = uid from sysusers where name = @newowner
  16269.                             and isaliased = 0 and name <> 'public'
  16270.     end
  16271.     if @newuid is null
  16272.     begin
  16273.         raiserror(15410, -1, -1, @newowner)
  16274.         return (1)
  16275.     end
  16276.  
  16277.     -- DO THE OWNER TRANSFER (WITH A WARNING) --
  16278.     raiserror(15477,-1,-1)
  16279.     begin transaction
  16280.     -- Locks Object and increments schema_ver.
  16281.     DBCC LockObjectSchema(@objname)
  16282.     -- drop permissions (they'll be incorrect with new owner) --
  16283.     delete syspermissions where id = @objid
  16284.     update sysobjects set uid = @newuid where id = @objid
  16285.     update sysobjects set uid = @newuid where parent_obj = @objid
  16286.     commit transaction
  16287.  
  16288.     -- SUCCESS MESSAGE --
  16289.     raiserror(15505,-1,-1)
  16290.     return 0    -- sp_changeobjectowner
  16291. go
  16292.  
  16293. -- GRANT PUBLIC ACCESS (SP'S DO INTERNAL PERMISSIONS CHECKS) --
  16294. grant execute on sp_grantdbaccess to public
  16295. grant execute on sp_revokedbaccess to public
  16296. grant execute on sp_adduser to public
  16297. grant execute on sp_dropuser to public
  16298. grant execute on sp_addalias to public
  16299. grant execute on sp_dropalias to public
  16300. grant execute on sp_addrole to public
  16301. grant execute on sp_droprole to public
  16302. grant execute on sp_dropgroup to public
  16303. grant execute on sp_addgroup to public
  16304. grant execute on sp_dropgroup to public
  16305. grant execute on sp_addapprole to public
  16306. grant execute on sp_approlepassword to public
  16307. grant execute on sp_setapprole to public
  16308. grant execute on sp_dropapprole to public
  16309. grant execute on sp_addrolemember to public
  16310. grant execute on sp_droprolemember to public
  16311. grant execute on sp_changegroup to public
  16312. grant execute on sp_change_users_login to public
  16313. grant execute on sp_changedbowner to public
  16314. grant execute on sp_changeobjectowner to public
  16315. go
  16316. /**********************  END DATABASE-ACCESS-SECURITY ************************/
  16317.  
  16318. /******************************************************************************
  16319. ************************  SECURITY-HELP-PROCEDURES  ***************************
  16320. ******************************************************************************/
  16321. checkpoint
  16322. go
  16323. if object_id('sp_helpsrvrole','P') IS NOT NULL
  16324.     drop procedure sp_helpsrvrole
  16325. if object_id('sp_srvrolepermission','P') IS NOT NULL
  16326.     drop procedure sp_srvrolepermission
  16327. if object_id('sp_helpsrvrolemember','P') IS NOT NULL
  16328.     drop procedure sp_helpsrvrolemember
  16329. if object_id('sp_helpdbfixedrole','P') IS NOT NULL
  16330.     drop procedure sp_helpdbfixedrole
  16331. if object_id('sp_dbfixedrolepermission','P') IS NOT NULL
  16332.     drop procedure sp_dbfixedrolepermission
  16333. if object_id('sp_helprolemember','P') IS NOT NULL
  16334.     drop procedure sp_helprolemember
  16335. if object_id('sp_helprole','P') IS NOT NULL
  16336.     drop procedure sp_helprole
  16337. if object_id('sp_helpntgroup','P') IS NOT NULL
  16338.     drop procedure sp_helpntgroup
  16339. if object_id('xp_logininfo','P') IS NOT NULL
  16340.     drop procedure xp_logininfo
  16341. go
  16342.  
  16343.  
  16344. ----------------------- sp_helpsrvrole ----------------------------------------
  16345.  
  16346. raiserror(15339,-1,-1,'sp_helpsrvrole')
  16347. go
  16348. CREATE PROCEDURE sp_helpsrvrole
  16349.     @srvrolename        sysname = NULL
  16350. AS
  16351.     if @srvrolename is not null
  16352.     begin
  16353.         -- VALIDATE GIVEN NAME
  16354.         if not exists (select * from master.dbo.spt_values
  16355.                 where name = @srvrolename and low = 0 and type = 'SRV')
  16356.         begin
  16357.             raiserror(15412, -1, -1, @srvrolename)
  16358.             return (1)
  16359.         end
  16360.  
  16361.         -- RESULT SET FOR SINGLE SERVER-ROLE
  16362.         select 'ServerRole' = v1.name, 'Description' = v2.name
  16363.             from master.dbo.spt_values v1, master.dbo.spt_values v2
  16364.             where v1.name = @srvrolename and
  16365.                   v1.low = 0 and 
  16366.                   v1.type = 'SRV' and
  16367.                   v2.low = -1 and
  16368.                   v2.type = 'SRV' and
  16369.                   v1.number = v2.number
  16370.     end
  16371.     else
  16372.     begin
  16373.         -- RESULT SET FOR ALL SERVER-ROLES
  16374.         select 'ServerRole' = v1.name, 'Description' = v2.name
  16375.             from master.dbo.spt_values v1, master.dbo.spt_values v2
  16376.             where v1.low = 0 and 
  16377.                   v1.type = 'SRV' and
  16378.                   v2.low = -1 and
  16379.                   v2.type = 'SRV' and
  16380.                   v1.number = v2.number
  16381.     end
  16382.  
  16383.     return (0) -- sp_helpsrvrole
  16384. go
  16385.  
  16386. ----------------------- sp_srvrolepermission ----------------------------------
  16387.  
  16388. raiserror(15339,-1,-1,'sp_srvrolepermission')
  16389. go
  16390. CREATE PROCEDURE sp_srvrolepermission
  16391.     @srvrolename       sysname = NULL
  16392. AS
  16393.     if @srvrolename is not null
  16394.     begin
  16395.         -- VALIDATE GIVEN NAME
  16396.         if not exists (select * from master.dbo.spt_values
  16397.                 where name = @srvrolename and low = 0 and type = 'SRV')
  16398.         begin
  16399.             raiserror(15412, -1, -1, @srvrolename)
  16400.             return (1)
  16401.         end
  16402.  
  16403.         -- RESULT SET FOR SINGLE SERVER-ROLE
  16404.         select 'ServerRole' = v1.name, 'Permission' = v2.name
  16405.             from master.dbo.spt_values v1, master.dbo.spt_values v2 
  16406.             where v1.name = @srvrolename and 
  16407.                   v1.low = 0 and 
  16408.                   v1.type = 'SRV' and
  16409.                   ((v2.type = 'SRV' and ((v1.number = 16 and v1.number <= v2.number) or (v1.number <> 16 and v1.number = v2.number))) or
  16410.                   (v2.type = 'DBR' and v1.number = 16)) and
  16411.                   v2.low > 0
  16412.             order by v1.name, v2.name
  16413.     end
  16414.     else
  16415.     begin
  16416.         -- RESULT SET FOR ALL SERVER-ROLES
  16417.         select 'ServerRole' = v1.name, 'Permission' = v2.name
  16418.             from master.dbo.spt_values v1, master.dbo.spt_values v2 
  16419.             where v1.low = 0 and 
  16420.                   v1.type = 'SRV' and
  16421.                   ((v2.type = 'SRV' and ((v1.number = 16 and v1.number <= v2.number) or (v1.number <> 16 and v1.number = v2.number))) or
  16422.                   (v2.type = 'DBR' and v1.number = 16)) and
  16423.                   v2.low > 0
  16424.             order by v1.name, v2.name
  16425.     end
  16426.  
  16427.     return (0) -- sp_srvrolepermission
  16428. go
  16429.  
  16430.  
  16431. ----------------------- sp_helpsrvrolemember ----------------------------------
  16432.  
  16433. raiserror(15339,-1,-1,'sp_helpsrvrolemember')
  16434. go
  16435. CREATE PROCEDURE sp_helpsrvrolemember
  16436.     @srvrolename       sysname = NULL
  16437. AS
  16438.     if @srvrolename is not null
  16439.     begin
  16440.         -- VALIDATE GIVEN NAME
  16441.         if not exists (select * from master.dbo.spt_values 
  16442.                 where name = @srvrolename and low = 0 and type = 'SRV')
  16443.         begin
  16444.             raiserror(15412, -1, -1, @srvrolename)
  16445.             return (1)
  16446.         end
  16447.  
  16448.         -- RESULT SET FOR SINGLE SERVER-ROLE
  16449.         select 'ServerRole' = spv.name, 'MemberName' = lgn.name, 'MemberSID' = lgn.sid
  16450.             from master.dbo.spt_values spv, master.dbo.sysxlogins lgn
  16451.             where spv.name = @srvrolename and 
  16452.                   spv.low = 0 and 
  16453.                   spv.type = 'SRV' and
  16454.                   lgn.srvid IS NULL and
  16455.                   spv.number & lgn.xstatus = spv.number
  16456.     end
  16457.     else
  16458.     begin
  16459.         -- RESULT SET FOR ALL SERVER-ROLES
  16460.         select 'ServerRole' = spv.name, 'MemberName' = lgn.name, 'MemberSID' = lgn.sid
  16461.             from master.dbo.spt_values spv, master.dbo.sysxlogins lgn
  16462.             where spv.low = 0 and 
  16463.                   spv.type = 'SRV' and
  16464.                   lgn.srvid IS NULL and
  16465.                   spv.number & lgn.xstatus = spv.number
  16466.     end
  16467.  
  16468.     return (0) -- sp_helpsrvrolemember
  16469. go
  16470.  
  16471. ----------------------- sp_helpdbfixedrole ----------------------------------------
  16472.  
  16473. raiserror(15339,-1,-1,'sp_helpdbfixedrole')
  16474. go
  16475. CREATE PROCEDURE sp_helpdbfixedrole
  16476.     @rolename        sysname = NULL
  16477. AS
  16478.     if @rolename is not null
  16479.     begin
  16480.         -- VALIDATE GIVEN NAME
  16481.         if not exists (select * from sysusers where name = @rolename
  16482.                         and uid >= 16384 and uid <= 16393)
  16483.         begin
  16484.             raiserror(15412, -1, -1, @rolename)
  16485.             return (1)
  16486.         end
  16487.  
  16488.         -- RESULT SET FOR SINGLE FIXED-ROLE
  16489.         select 'DbFixedRole' = usr.name, 'Description' = spv.name
  16490.             from sysusers usr, master.dbo.spt_values spv
  16491.             where usr.name = @rolename and
  16492.                   usr.uid >= 16384 and
  16493.                   usr.uid <= 16393 and
  16494.                   usr.uid = spv.number and
  16495.                   spv.type = 'DBR' and
  16496.                   spv.low = -1
  16497.     end
  16498.     else
  16499.     begin
  16500.         -- RESULT SET FOR ALL FIXED-ROLES
  16501.         select 'DbFixedRole' = usr.name, 'Description' = spv.name
  16502.             from sysusers usr, master.dbo.spt_values spv
  16503.             where usr.uid >= 16384 and
  16504.                   usr.uid <= 16393 and
  16505.                   usr.uid = spv.number and
  16506.                   spv.type = 'DBR' and
  16507.                   spv.low = -1
  16508.     end
  16509.  
  16510.     return (0) -- sp_helpdbfixedrole
  16511. go
  16512.  
  16513.  
  16514. ----------------------- sp_dbfixedrolepermission ------------------------------
  16515.  
  16516. raiserror(15339,-1,-1,'sp_dbfixedrolepermission')
  16517. go
  16518. CREATE PROCEDURE sp_dbfixedrolepermission
  16519.     @rolename       sysname = NULL
  16520. AS
  16521.     if @rolename is not null
  16522.     begin
  16523.         -- VALIDATE GIVEN NAME
  16524.         if not exists (select * from sysusers where name = @rolename
  16525.                         and uid >= 16384 and uid <= 16393)
  16526.         begin
  16527.             raiserror(15412, -1, -1, @rolename)
  16528.             return (1)
  16529.         end
  16530.  
  16531.         -- RESULT SET FOR SINGLE FIXED-ROLE
  16532.         select 'DbFixedRole' = usr.name, 'Permission' = spv.name 
  16533.             from sysusers usr, master.dbo.spt_values spv
  16534.             where usr.name = @rolename and
  16535.                   usr.uid >= 16384 and
  16536.                   usr.uid <= 16393 and
  16537.                   spv.type = 'DBR' and
  16538.                   ((usr.uid = 16384 and spv.number >= 16384 and spv.number < 16392) or (usr.uid <> 16384 and usr.uid = spv.number)) and
  16539.                   spv.low > 0
  16540.             order by usr.name, spv.name
  16541.     end
  16542.     else
  16543.     begin
  16544.         -- RESULT SET FOR ALL FIXED-ROLES
  16545.         select 'DbFixedRole' = usr.name, 'Permission' = spv.name 
  16546.             from sysusers usr, master.dbo.spt_values spv
  16547.             where usr.uid >= 16384 and
  16548.                   usr.uid <= 16393 and
  16549.                   spv.type = 'DBR' and
  16550.                   ((usr.uid = 16384 and spv.number >= 16384 and spv.number < 16392) or (usr.uid <> 16384 and usr.uid = spv.number)) and
  16551.                   spv.low > 0
  16552.             order by usr.name, spv.name
  16553.     end
  16554.  
  16555.     return (0) -- sp_dbfixedrolepermission
  16556. go
  16557.  
  16558.  
  16559. ----------------------- sp_helprolemember -------------------------------------
  16560.  
  16561. raiserror(15339,-1,-1,'sp_helprolemember')
  16562. go
  16563. CREATE PROCEDURE sp_helprolemember
  16564.     @rolename       sysname = NULL
  16565. AS
  16566.     if @rolename is not null
  16567.     begin
  16568.         -- VALIDATE GIVEN NAME
  16569.         if not exists (select * from sysusers where name = @rolename and issqlrole = 1)
  16570.         begin
  16571.             raiserror(15409, -1, -1, @rolename)
  16572.             return (1)
  16573.         end
  16574.  
  16575.         -- RESULT SET FOR SINGLE ROLE
  16576.         select DbRole = g.name, MemberName = u.name, MemberSID = u.sid
  16577.             from sysusers u, sysusers g, sysmembers m
  16578.             where g.name = @rolename
  16579.                 and g.uid = m.groupuid
  16580.                 and g.issqlrole = 1
  16581.                 and u.uid = m.memberuid
  16582.             order by 1, 2
  16583.     end
  16584.     else
  16585.     begin
  16586.         -- RESULT SET FOR ALL ROLES
  16587.         select DbRole = g.name, MemberName = u.name, MemberSID = u.sid
  16588.             from sysusers u, sysusers g, sysmembers m
  16589.             where   g.uid = m.groupuid
  16590.                 and g.issqlrole = 1
  16591.                 and u.uid = m.memberuid
  16592.             order by 1, 2
  16593.     end
  16594.  
  16595.     return (0) -- sp_helprolemember
  16596. go
  16597.  
  16598.  
  16599. ----------------------- sp_helprole -------------------------------------------
  16600.  
  16601. raiserror(15339,-1,-1,'sp_helprole')
  16602. go
  16603. CREATE PROCEDURE sp_helprole
  16604.     @rolename       sysname = NULL
  16605. AS
  16606.     if @rolename is not null
  16607.     begin
  16608.         -- VALIDATE GIVEN NAME
  16609.         if not exists (select * from sysusers where name = @rolename and (issqlrole = 1 or isapprole = 1))
  16610.         begin
  16611.             raiserror(15409, -1, -1, @rolename)
  16612.             return (1)
  16613.         end
  16614.  
  16615.         -- RESULT SET FOR SINGLE ROLE
  16616.         select 'RoleName' = name, 'RoleId' = uid, 'IsAppRole' = isapprole
  16617.             from sysusers where (name = @rolename) and (issqlrole = 1 or isapprole = 1)
  16618.     end
  16619.     else
  16620.     begin
  16621.         -- RESULT SET FOR ALL ROLES
  16622.         select 'RoleName' = name, 'RoleId' = uid, 'IsAppRole' = isapprole
  16623.             from sysusers where issqlrole = 1 or isapprole = 1
  16624.     end
  16625.  
  16626.     return (0) -- sp_helprole
  16627. go
  16628.  
  16629.  
  16630. ----------------------- sp_helpntgroup ----------------------------------------
  16631.  
  16632. raiserror(15339,-1,-1,'sp_helpntgroup')
  16633. go
  16634. CREATE PROCEDURE sp_helpntgroup
  16635.     @ntname       sysname = NULL
  16636. AS
  16637.     if @ntname is not null
  16638.     begin
  16639.         -- VALIDATE GIVEN NAME
  16640.         if not exists (select * from sysusers where name = @ntname and isntgroup = 1)
  16641.         begin
  16642.             raiserror(15420, -1, -1, @ntname)
  16643.             return (1)
  16644.         end
  16645.  
  16646.         -- RESULT SET FOR SINGLE GROUP
  16647.         select 'NTGroupName' = name, 'NtGroupId' = uid, 'SID' = sid, 'HasDbAccess' = hasdbaccess
  16648.             from sysusers where name = @ntname and isntgroup = 1
  16649.     end
  16650.     else
  16651.     begin
  16652.         -- RESULT SET FOR ALL GROUPS
  16653.         select 'NTGroupName' = name, 'NtGroupId' = uid, 'SID' = sid, 'HasDbAccess' = hasdbaccess
  16654.             from sysusers where isntgroup = 1
  16655.     end
  16656.  
  16657.     return (0) -- sp_helpntgroup
  16658. go
  16659.  
  16660. ------------------------------- xp_logininfo ----------------------------------
  16661.  
  16662. create proc xp_logininfo
  16663.     @acctname        sysname = null,                -- IN: NT login name
  16664.     @option            varchar(10) = null,            -- IN: 'all' | 'members' | null
  16665.     @privelege        varchar(10) = 'Not wanted' OUTPUT    -- OUT: 'admin' | 'user' | null
  16666. as
  16667.     -- VALIDATE PARAMETERS --
  16668.     if (@acctname is null AND (@option is not null OR (@privelege is null OR @privelege <> 'Not wanted')))
  16669.         OR ((@option is null OR @option <> 'all') AND (@privelege is null OR @privelege <> 'Not wanted'))
  16670.         OR (@option is not null and @option not in ('all', 'members'))
  16671.     begin
  16672.         raiserror(15600,-1,-1,'xp_logininfo')
  16673.         return 1
  16674.     end
  16675.  
  16676.     -- HANDLE CASE WHERE NO @acctname GIVEN --
  16677.     if (@acctname is null)
  16678.     begin
  16679.         select    'account name' = loginname,
  16680.                 'type' = convert(varchar(8), case when isntuser = 1 then 'user' else 'group' end),
  16681.                 'privelege' = convert(varchar(8), case when sysadmin = 1 then 'admin' else 'user' end),
  16682.                 'mapped login name' = loginname,
  16683.                 'permission path' = convert(sysname, null)
  16684.         from master..syslogins where isntname = 1 and hasaccess = 1
  16685.         order by 3, 1
  16686.         return @@error
  16687.     end
  16688.  
  16689.     -- HANDLE 'members' QUERY --
  16690.     if (@option = 'members')
  16691.     begin
  16692.         declare @priv varchar(8)
  16693.         select @priv = case when sysadmin = 1 then 'admin' else 'user' end
  16694.             from master..syslogins where isntname = 1 and loginname = @acctname and hasaccess = 1
  16695.         if @priv is not null
  16696.             select    'account name' = domain+N'\'+name,
  16697.                     'type' = convert(varchar(8), case when sidtype = 1 then 'user' else 'group' end),
  16698.                     'privelege' = @priv,
  16699.                     'mapped login name' = domain+N'\'+name,
  16700.                     'permission path' = @acctname
  16701.             from OpenRowset(NetGroupGetMembers, @acctname) order by 3, 1
  16702.         else
  16703.             select    'account name' = convert(sysname, null),
  16704.                     'type' = convert(varchar(8), null),
  16705.                     'privelege' = @priv,
  16706.                     'mapped login name' = convert(sysname, null),
  16707.                     'permission path' = convert(sysname, null)
  16708.             where 0=1    -- empty result set
  16709.         return @@error
  16710.     end
  16711.  
  16712.     -- CREATE TEMP TABLE AND POPULATE WITH THE REQUIRED DATA --
  16713.     create table #nt (name sysname, sid varbinary(85), sidtype int)
  16714.     insert #nt select loginname, sid, isntgroup + 1 from master..syslogins
  16715.             where isntname = 1 and loginname = @acctname
  16716.     insert #nt select distinct domain+N'\'+name, sid, sidtype
  16717.             from OpenRowset(NetUserGetGroups, @acctname)
  16718.     if @@error <> 0
  16719.         return @@error
  16720.     -- IF ANY DENY, THEN NO ACCESS --
  16721.     if exists (select * from master..syslogins where sid in (select #nt.sid from #nt) and denylogin = 1)
  16722.         delete #nt
  16723.  
  16724.     -- HANDLE CASE WHERE OUTPUT REQUESTED --
  16725.     if (@privelege is null OR @privelege <> 'Not wanted')
  16726.     begin
  16727.         select @privelege = case max(sysadmin)
  16728.             when 1 then 'admin'
  16729.             when 0 then 'user'
  16730.             else NULL end
  16731.         from master..syslogins where isntname = 1 and hasaccess = 1
  16732.             AND sid in (select sid from #nt)
  16733.         return @@error
  16734.     end
  16735.  
  16736.     -- GET NT TYPE FOR NEXT OPTIONS --
  16737.     declare @type varchar(8)
  16738.     select @type = case when get_sid('\U'+@acctname, NULL) is null then 'group' else 'user' end
  16739.  
  16740.     -- HANDLE 'all' QUERY --
  16741.     if (@option = 'all')
  16742.     begin
  16743.         select    'account name' = @acctname,
  16744.                 'type' = @type,
  16745.                 'privelege' = convert(varchar(8), case when sysadmin = 1 then 'admin' else 'user' end),
  16746.                 'mapped login name' = @acctname,
  16747.                 'permission path' = case when l.loginname = @acctname then NULL else l.loginname end
  16748.         from master..syslogins l join #nt n on l.isntname = 1 and l.sid = n.sid
  16749.         where l.loginname = n.name and hasaccess = 1
  16750.         order by 3, 5
  16751.         return @@error
  16752.     end
  16753.  
  16754.     -- HANDLE DEFAULT QUERY --
  16755.     select    TOP 1
  16756.             'account name' = @acctname,
  16757.             'type' = @type,
  16758.             'privelege' = convert(varchar(8), case when sysadmin = 1 then 'admin' else 'user' end),
  16759.             'mapped login name' = @acctname,
  16760.             'permission path' = case when l.loginname = @acctname then NULL else l.loginname end
  16761.     from master..syslogins l join #nt n on l.isntname = 1 and l.sid = n.sid
  16762.     where l.loginname = n.name and hasaccess = 1
  16763.     order by 3, 5
  16764.     return @@error
  16765. go
  16766.  
  16767. -- GRANT PUBLIC ACCESS --
  16768. grant execute on sp_helpsrvrole            to public
  16769. grant execute on sp_srvrolepermission      to public
  16770. grant execute on sp_helpsrvrolemember      to public
  16771. grant execute on sp_helpdbfixedrole           to public
  16772. grant execute on sp_dbfixedrolepermission  to public
  16773. grant execute on sp_helprolemember         to public
  16774. grant execute on sp_helprole               to public
  16775. grant execute on sp_helpntgroup            to public
  16776. -- NOTE: No grant for xp_logininfo! (it has no internal perm checks)
  16777. go
  16778. /************************  END-SECURITY-HELP-PROCEDURES  *********************/
  16779.  
  16780. /******************************************************************************
  16781. **************************  SYSSERVER-STORED-PROCS  ***************************
  16782. ******************************************************************************/
  16783. checkpoint
  16784. go
  16785. if object_id('sp_addlinkedserver','P') IS NOT NULL
  16786.     drop procedure sp_addlinkedserver
  16787. if object_id('sp_dropserver','P') IS NOT NULL
  16788.     drop procedure sp_dropserver
  16789. if object_id('sp_serveroption','P') IS NOT NULL
  16790.     drop procedure sp_serveroption
  16791. if object_id('sp_addserver','P') IS NOT NULL
  16792.     drop procedure sp_addserver
  16793. if object_id('sp_setnetname','P') IS NOT NULL
  16794.     drop procedure sp_setnetname
  16795. if object_id('sp_helpserver','P') IS NOT NULL
  16796.     drop procedure sp_helpserver
  16797. if object_id('sp_helplinkedsrvlogin','P') IS NOT NULL
  16798.     drop procedure sp_helplinkedsrvlogin
  16799. go
  16800.  
  16801.  
  16802. ----------------------------- sp_addlinkedserver ------------------------------
  16803.  
  16804. raiserror(15339,-1,-1,'sp_addlinkedserver')
  16805. go
  16806. create procedure sp_addlinkedserver
  16807.     @server         sysname,                -- server name
  16808.     @srvproduct     nvarchar(128) = NULL,   -- product name (dflt to ss)
  16809.     @provider       nvarchar(128) = NULL,   -- oledb provider name
  16810.     @datasrc        nvarchar(4000) = NULL,  -- oledb datasource property
  16811.     @location       nvarchar(4000) = NULL,  -- oledb location property
  16812.     @provstr        nvarchar(4000) = NULL,  -- oledb provider-string property
  16813.     @catalog        sysname = NULL          -- oledb catalog property
  16814. as
  16815.     -- VARIABLES
  16816.     declare @retcode    int,
  16817.             @srvid      smallint,
  16818.             @srvstat    smallint
  16819.  
  16820.     -- DISALLOW USER TRANSACTION
  16821.     set implicit_transactions off
  16822.     if @@trancount > 0
  16823.     begin
  16824.         raiserror(15002,-1,-1,'sp_addlinkedserver')
  16825.         return (1)
  16826.     end
  16827.  
  16828.     -- CHECK PERMISSIONS
  16829.     if not (is_srvrolemember('setupadmin') = 1)
  16830.     begin
  16831.         raiserror(15232,-1,-1)
  16832.         return (1)
  16833.     end
  16834.  
  16835.     -- VALIDATE SERVER NAME
  16836.     execute @retcode = sp_validname @server
  16837.     if @retcode <> 0
  16838.         return (1)
  16839.  
  16840.     -- SET DEFAULT STATUS BITS
  16841.     select @srvstat = 32 | 128   -- local login mapping = 32, data access = 128
  16842.  
  16843.     -- VALIDATE OLEDB PARAMETERS
  16844.     if @provider is null
  16845.     begin
  16846.         -- NO PROVIDER MEANS CANNOT SPECIFY ANY PROPERTIES!
  16847.         if @datasrc is not null or @location is not null or @provstr is not null or @catalog is not null
  16848.         begin
  16849.             raiserror(15426,-1,-1)
  16850.             return (1)
  16851.         end
  16852.  
  16853.         -- THIS MUST BE A WELL-KNOWN SERVER TYPE (DEFAULT IS SS)
  16854.         if @srvproduct is null OR lower(@srvproduct) = N'sql server'
  16855.         begin
  16856.             select @srvproduct = N'SQL Server'  -- force case to be this
  16857.             select @provider = N'SQLOLEDB'      -- SQL Server provider (LUXOR)
  16858.             select @datasrc = @server           -- datasrc is (network) server name
  16859.                         -- For SQL Server, we want rpc in/out by default
  16860.             select @srvstat = @srvstat | 1 | 64
  16861.                         -- rpc = 1, rpc out = 64
  16862.         end
  16863.         else            -- ADD OTHER WELL-KNOWN SOURCES HERE
  16864.         begin
  16865.             raiserror(15427,-1,-1,@srvproduct)
  16866.             return (1)
  16867.         end
  16868.     end
  16869.     else if @srvproduct in (N'SQL Server')  -- WELL-KNOWN SOURCES
  16870.     begin
  16871.         -- ILLEGAL TO SPECIFY PROVIDER/PROPERTIES FOR WELL-KNOWN SOURCES
  16872.         raiserror(15428,-1,-1,@srvproduct)
  16873.         return (1)
  16874.     end
  16875.     else if @srvproduct is null or lower(@srvproduct) like N'%sql server%'
  16876.     begin
  16877.         raiserror(15429,-1,-1,@srvproduct)
  16878.         return (1)
  16879.     end
  16880.  
  16881.     -- CHECK IF SERVER ALREADY EXISTS
  16882.     if exists (select * from master.dbo.sysservers where srvname = @server)
  16883.     begin
  16884.         raiserror(15028,-1,-1,@server)
  16885.         return (1)
  16886.     end
  16887.  
  16888.     -- GET SERVER ID FOR NEW ROW
  16889.     if not exists (select * from master.dbo.sysservers where srvid = 1)
  16890.         select @srvid = 1
  16891.     else
  16892.         select @srvid = min(s.srvid)+1 from master.dbo.sysservers s
  16893.             where s.srvid < 32767 and not exists
  16894.                 (select * from master.dbo.sysservers s2 where s2.srvid = s.srvid+1)
  16895.     if @srvid is null
  16896.     begin
  16897.         raiserror(15430,-1,-1)
  16898.         return (1)
  16899.     end
  16900.  
  16901.     -- ADD ROW TO SYSSERVERS
  16902.     insert master.dbo.sysservers select @srvid, @srvstat, @server, @srvproduct,
  16903.                 @provider, @datasrc, @location, @provstr, getdate(), NULL, NULL, @catalog
  16904.  
  16905.     -- ADD DEFAULT MAPPING FOR OUTGOING EVENTS
  16906.     insert into master.dbo.sysxlogins select
  16907.         @srvid, NULL, 192, getdate(), getdate(), NULL, NULL, 0, NULL
  16908.  
  16909.     -- SUCCESS
  16910.     raiserror(15506,-1,-1)
  16911.     return (0) -- sp_addlinkedserver
  16912. go
  16913.  
  16914.  
  16915. ------------------------------- sp_dropserver ---------------------------------
  16916.  
  16917. raiserror(15339,-1,-1,'sp_dropserver')
  16918. go
  16919. create procedure sp_dropserver
  16920.     @server     sysname,            -- server name
  16921.     @droplogins char(10) = NULL     -- drop all related logins?
  16922. as
  16923.     declare @ret int
  16924.  
  16925.     -- DISALLOW USER TRANSACTION
  16926.     set implicit_transactions off
  16927.     if @@trancount > 0
  16928.     begin
  16929.         raiserror(15002,-1,-1,'sp_dropserver')
  16930.         return (1)
  16931.     end
  16932.  
  16933.     -- CHECK PERMISSIONS
  16934.     if not (is_srvrolemember('setupadmin') = 1)
  16935.     begin
  16936.         raiserror(15232,-1,-1)
  16937.         return (1)
  16938.     end
  16939.  
  16940.  
  16941.     -- CHECK SERVER NAME / GET SERVER ID
  16942.     declare @srvid smallint
  16943.     select @srvid = srvid from master.dbo.sysservers where srvname = @server
  16944.     if @srvid is null
  16945.     begin
  16946.         raiserror(15015,-1,-1,@server)
  16947.         return (1)
  16948.     end
  16949.  
  16950.     -- CHECK @droplogins PARAMETER (FOR RELATED SYSREMOTELOGINS ROWS)
  16951.     if @droplogins is null
  16952.     begin
  16953.         -- DONT consider default mapping for outgoing events
  16954.         if exists (select * from master.dbo.sysxlogins
  16955.                     where srvid = @srvid and 
  16956.                           not(ishqoutmap = 1 and 
  16957.                               xstatus&192 = 192 and 
  16958.                               sid is null and 
  16959.                               name is null and 
  16960.                               password is null))
  16961.         begin
  16962.             raiserror(15190,-1,-1,@server)
  16963.             return (1)
  16964.         end
  16965.     end
  16966.     else if @droplogins <> 'droplogins'
  16967.     begin
  16968.         raiserror(15191,-1,-1)
  16969.         return (1)
  16970.     end
  16971.  
  16972.     -- CHECK TO SEE IF THE SERVER IS USED BY REPLICATION.
  16973.     if object_id('master.dbo.sp_MSrepl_check_server') is not null
  16974.     begin
  16975.         execute @ret = master.dbo.sp_MSrepl_check_server @server
  16976.         if @ret <> 0 or @@error <> 0
  16977.             return 1
  16978.     end
  16979.  
  16980.     -- DROP THE SERVER (ALONG WITH ANY REMOTE LOGINS)
  16981.     begin transaction
  16982.     delete master.dbo.sysxlogins where srvid = @srvid
  16983.     if @@rowcount > 0
  16984.         raiserror(15507,-1,-1,@server)
  16985.     delete master.dbo.sysservers where srvid = @srvid
  16986.     commit transaction
  16987.     -- SUCCESS
  16988.     raiserror(15508,-1,-1)
  16989.     return (0) -- sp_dropserver
  16990. go
  16991.  
  16992.  
  16993. ------------------------------ sp_serveroption --------------------------------
  16994.  
  16995. raiserror(15339,-1,-1,'sp_serveroption')
  16996. go
  16997. -- ANSI_NULLS on for creation of sp_serveroption
  16998. Set ansi_nulls on
  16999. go
  17000. create procedure sp_serveroption
  17001.     @server     sysname = NULL,     -- server name to change (none displays possible options)
  17002.     @optname    varchar(35) = NULL, -- option name to turn on/off (none displays current)
  17003.     @optvalue   varchar(10) = NULL    -- true or false, on or off (none displays current)
  17004. as
  17005.     -- VARIABLES
  17006.     declare @srvid          int,        -- id of the server
  17007.             @statvalue      smallint,   -- status bit of option
  17008.             @optcount       int,         -- count of matching options
  17009.             --sum of all settable options
  17010.             @allsetopt        int
  17011.  
  17012.     ------------------------------------------------------
  17013.     -- NOTE: NOT ALL SERVER OPTIONS ARE SETTABLE
  17014.     ------------------------------------------------------
  17015.     select @allsetopt=number from master.dbo.spt_values
  17016.         where type = 'A' and name = 'ALL SETTABLE OPTIONS'
  17017.  
  17018.     -- IF NO SERVER NAME, JUST LIST POSSIBLE OPTIONS
  17019.     if @server is null
  17020.     begin
  17021.         raiserror(15509,-1,-1)
  17022.         select server_option = name from master.dbo.spt_values
  17023.             where type = 'A' 
  17024.             and number & @allsetopt <> 0
  17025.             and number not in (-1,@allsetopt) order by name
  17026.         return (0)
  17027.     end
  17028.  
  17029.      -- LOOK UP SERVER ID (ERROR IF NOT FOUND)
  17030.     select @srvid = srvid from master.dbo.sysservers where srvname = @server
  17031.     if @srvid is NULL
  17032.     begin
  17033.         raiserror(15015,-1,-1,@server)
  17034.         return (1)
  17035.     end
  17036.  
  17037.     -- IF NO OPTION SUPPLIED, DISPLAY CURRENT SETTINGS
  17038.     if @optname is null
  17039.     begin
  17040.         select 'The following options are set:' =v.name
  17041.         from master.dbo.spt_values v, master.dbo.sysservers s
  17042.         where srvid = @srvid
  17043.             and (v.number & s.srvstatus)=v.number
  17044.             and (v.number & @allsetopt) <> 0
  17045.             and v.number not in (-1, @allsetopt)
  17046.             and v.type = 'A'
  17047.         return(0)
  17048.     end
  17049.  
  17050.     -- CHECK REMAINING PARAMETERS
  17051.     select @optvalue = lower(@optvalue)
  17052.     if @optvalue is not NULL and @optvalue not in ('true','false','on','off')
  17053.     begin
  17054.         raiserror(15229,-1,-1)
  17055.         return (1)
  17056.     end
  17057.  
  17058.     -- MUST HAVE EXACTLY ONE MATCH FOR OPTION VALUE
  17059.     select @optcount = count(*) from master.dbo.spt_values
  17060.         where name like @optname 
  17061.             and type = 'A' 
  17062.             and number & @allsetopt <> 0
  17063.             and number not in (-1,@allsetopt)
  17064.     if @optcount = 0
  17065.     begin
  17066.         raiserror(15230,-1,-1,@optname)
  17067.         return (1)
  17068.     end
  17069.     if @optcount > 1
  17070.     begin
  17071.         raiserror(15231,-1,-1,@optname)
  17072.         print ' '
  17073.         select duplicate_option = name from master.dbo.spt_values
  17074.         where name like @optname 
  17075.             and type = 'A'
  17076.             and number & @allsetopt <> 0 
  17077.             and number not in (-1,@allsetopt)
  17078.         return (1)
  17079.     end
  17080.  
  17081.     -- CHECK PERMISSIONS (UPDATE PART RESTRICTED)
  17082.     if not (is_srvrolemember('setupadmin') = 1)
  17083.     begin
  17084.         raiserror(15232,-1,-1)
  17085.         return (1)
  17086.     end
  17087.  
  17088.     -- DISALLOW USER TRANSACTION
  17089.     set implicit_transactions off
  17090.     if @@trancount > 0
  17091.     begin
  17092.         raiserror(15002,-1,-1,'sp_serveroption')
  17093.         return (1)
  17094.     end
  17095.  
  17096.     -- GET THE BIT VALUE FOR THE OPTION
  17097.     select @statvalue = number from master.dbo.spt_values
  17098.         where name like @optname and type = 'A'
  17099.  
  17100.     --  JUST WANT TO SEE CURRENT SETTING OF SPECIFIED OPTION.
  17101.     if @optvalue is null
  17102.     begin
  17103.           select OptionName = v.name
  17104.  
  17105.                 ,CurrentSetting =
  17106.                    CASE
  17107.                       When (v.number & s.srvstatus) = v.number
  17108.                          Then 'ON'
  17109.                       When NOT
  17110.                            (v.number & s.srvstatus) = v.number
  17111.                          Then 'off'
  17112.                    END
  17113.  
  17114.              from master.dbo.spt_values v, master.dbo.sysservers s
  17115.                 where s.srvid = @srvid and v.number = @statvalue and 
  17116.                     v.type = 'A'
  17117.        return (0)
  17118.     end
  17119.  
  17120.     -- ONLY ONE SERVER MAY BE A DISTRIBUTION SERVER
  17121.     if @optname like 'dist'
  17122.     begin
  17123.         if @optvalue in ('true', 'on')
  17124.         begin
  17125.         declare @distributor sysname
  17126.             select @distributor = srvname from master.dbo.sysservers
  17127.                             where (srvstatus & @statvalue) <> 0
  17128.         if @distributor is not null
  17129.             begin
  17130.                 raiserror(14099,-1,-1, @distributor)
  17131.                 return (1)
  17132.             end
  17133.         end
  17134.      end
  17135.  
  17136.     -- CANNOT MAKE A SYSTEM SERVER INTO NON-SYSTEM --
  17137.     if @optname like 'system' and @optvalue not in ('true','on')
  17138.     begin
  17139.         raiserror(15232,-1,-1)
  17140.         return (1)
  17141.     end
  17142.  
  17143.     -- UPDATE SYSSERVERS
  17144.     if @optvalue in ('true','on')
  17145.         update master.dbo.sysservers set
  17146.                 srvstatus = srvstatus | @statvalue, schemadate = getdate()
  17147.             where srvid = @srvid
  17148.     else
  17149.         update master.dbo.sysservers set
  17150.                 srvstatus = srvstatus & ~@statvalue, schemadate = getdate()
  17151.             where srvid = @srvid
  17152.  
  17153.     -- RETURN SUCCESS
  17154.     return (0) -- sp_serveroption
  17155. go
  17156. -- ANSI_NULLS off for after creation of sp_serveroption
  17157. Set ansi_nulls off
  17158. go
  17159.  
  17160.  
  17161. -------------------------------- sp_addserver ---------------------------------
  17162.  
  17163. raiserror(15339,-1,-1,'sp_addserver')
  17164. go
  17165. create procedure sp_addserver
  17166.     @server         sysname,            --server name
  17167.     @local          varchar(10) = NULL, -- NULL or 'local'
  17168.     @duplicate_ok   varchar(13) = NULL  -- NULL or 'duplicate_ok'
  17169. as
  17170.     -- VARS
  17171.     declare @retcode        int,
  17172.             @statvalue      smallint
  17173.  
  17174.     -- CHECK IF SERVER ALREADY EXISTS
  17175.     if exists (select * from master.dbo.sysservers where srvname = @server)
  17176.     begin
  17177.         if @duplicate_ok = 'duplicate_ok'
  17178.             return (0)
  17179.         raiserror(15028,-1,-1,@server)
  17180.         return (1)
  17181.     end
  17182.  
  17183.     -- VALIDATE @local PARAMETER
  17184.     if @local is not null
  17185.     begin
  17186.         select @local = lower(@local)
  17187.         if @local <> 'local'
  17188.         begin
  17189.             raiserror(15379,-1,-1,@local)
  17190.             return (1)
  17191.         end
  17192.  
  17193.         -- ERROR IF ALREADY HAVE A LOCAL SERVER NAME
  17194.         if exists (select * from master.dbo.sysservers where srvid = 0)
  17195.         begin
  17196.             raiserror(15090,-1,-1)
  17197.             return (1)
  17198.         end
  17199.     end
  17200.  
  17201.     -- ADD THE SERVER (CHECKS PERMISSIONS, ETC)
  17202.     execute @retcode = sp_addlinkedserver @server
  17203.     if @retcode <> 0
  17204.         return @retcode
  17205.  
  17206.     -- SET THE SERVER ID IF LOCAL OPTION SPECIFIED
  17207.     if @local = 'local'
  17208.     begin
  17209.         declare @srvid smallint
  17210.         -- UPDATE DEFAULT MAPPING CREATED BY sp_addlinkedserver
  17211.         select @srvid = srvid from master.dbo.sysservers where srvname = @server
  17212.         update master.dbo.sysxlogins set srvid = 0 where srvid = @srvid
  17213.         update master.dbo.sysservers 
  17214.             set srvid = 0, 
  17215.                 schemadate = getdate()
  17216.             where srvname = @server
  17217.     end
  17218.  
  17219.     -- FOR COMPATIBILITY, TURN OFF THE data access SERVER OPTION
  17220.     execute @retcode = sp_serveroption @server, 'data access', 'off'
  17221.     if @retcode <> 0
  17222.         return @retcode
  17223.  
  17224.     -- FOR COMPATIBILITY: make rpc-s behave as in 6.5
  17225.     select @statvalue = number from master..spt_values
  17226.     where name = 'local login mapping' and type = 'A'
  17227.  
  17228.     --SET 'local login mapping', 'off'
  17229.     update master.dbo.sysservers 
  17230.     set srvstatus = srvstatus & ~@statvalue, schemadate = getdate()
  17231.             where srvname = @server
  17232.  
  17233.     if @retcode <> 0
  17234.         return @retcode
  17235.  
  17236.     -- SUCCESS (MESSAGE ALREADY PRINTED)
  17237.     return (0) -- sp_addserver
  17238. go
  17239.  
  17240.  
  17241. ------------------------------- sp_setnetname ---------------------------------
  17242.  
  17243. raiserror(15339,-1,-1,'sp_setnetname')
  17244. go
  17245. create procedure sp_setnetname  --- 1995/12/22 13:07
  17246.      @server    sysname    -- server name
  17247.     ,@netname    sysname    -- new net name
  17248. as
  17249.     -- DISALLOW USER TRANSACTION
  17250.     set implicit_transactions off
  17251.     if @@trancount > 0
  17252.     begin
  17253.         raiserror(15002,-1,-1,'sp_setnetname')
  17254.         return (1)
  17255.     end
  17256.  
  17257.     -- CHECK PERMISSIONS
  17258.     if not (is_srvrolemember('setupadmin') = 1)
  17259.     begin
  17260.         raiserror(15232,-1,-1)
  17261.         return (1)
  17262.     end
  17263.  
  17264.     -- CHECK SERVER NAME (MUST BE A SQL SERVER!)
  17265.     if not exists (select * from master.dbo.sysservers
  17266.                     where srvname = @server and srvproduct = N'SQL Server')
  17267.     begin
  17268.         raiserror(15015,-1,-1,@server)
  17269.         return (1)
  17270.     end
  17271.  
  17272.     -- DO THE UPDATE
  17273.     update master.dbo.sysservers set datasource = @netname, schemadate = getdate()
  17274.         where srvname = @server
  17275.  
  17276.     -- SUCCESS
  17277.     raiserror(15510,-1,-1)
  17278.     return (0) -- sp_setnetname
  17279. go
  17280.  
  17281.  
  17282. ------------------------------- sp_helpserver ---------------------------------
  17283.  
  17284. raiserror(15339,-1,-1,'sp_helpserver')
  17285. go
  17286. create procedure sp_helpserver
  17287.     @server         sysname = NULL,         -- server name
  17288.     @optname        varchar(35) = NULL,     -- option name to limit results
  17289.     @show_topology  varchar(1) = NULL       -- 't' to show topology coordinates
  17290. as
  17291.     -- PRELIMINARY
  17292.     set nocount on
  17293.     declare @optbit     int,
  17294.             @bitdesc    sysname,
  17295.             @curbit     int,
  17296.             --sum of all settable options
  17297.             @allsetopt        int
  17298.  
  17299.     select @allsetopt=number    from master.dbo.spt_values 
  17300.         where type = 'A'  and name    = 'ALL SETTABLE OPTIONS'
  17301.  
  17302.     -- CHECK IF REQUESTED SERVER(S) EXIST
  17303.     if not exists (select * from master.dbo.sysservers where 
  17304.         (@server is null or srvname = @server))
  17305.     begin
  17306.         if @server is null
  17307.             raiserror(15205,-1,-1)
  17308.         else
  17309.             raiserror(15015,-1,-1,@server)
  17310.         return (1)
  17311.     end
  17312.  
  17313.     -- GET THE BIT VALUE(S) FOR THE OPTION REQUESTED
  17314.     if @optname is not null
  17315.     begin
  17316.         select @optbit = number from master.dbo.spt_values
  17317.             where type = 'A' 
  17318.                 and name = @optname 
  17319.                 and number & @allsetopt <> 0
  17320.                 and number not in (-1, @allsetopt)
  17321.         if @optbit is null
  17322.         begin
  17323.             raiserror(15206,-1,-1,@optname)
  17324.             return(1)
  17325.         end
  17326.     end
  17327.     else
  17328.         select @optbit = -1     -- 0xffffffff
  17329.  
  17330.     -- MAKE WORK COPY OF RELEVANT PART OF SYSSERVERS
  17331.     select name = srvname, network = srvnetname, status = convert(varchar(70), ''),
  17332.             id = srvid, srvstat = srvstatus, topx = topologyx, topy = topologyy
  17333.         into #spt_server
  17334.         from master.dbo.sysservers
  17335.         where (@server is null or srvname = @server) and (@optname is null or srvstatus & @optbit <> 0)
  17336.  
  17337.     -- SET THE STATUS FIELD
  17338.     select @curbit = 1
  17339.     while @curbit < 0x10000 -- bit field is a smallint
  17340.     begin
  17341.         select @bitdesc = null
  17342.         select @bitdesc = name from master.dbo.spt_values 
  17343.         where type = 'A' and number = @curbit and (number & @allsetopt) <> 0
  17344.         if @bitdesc is not null
  17345.             update #spt_server set status = status + ',' + @bitdesc where srvstat & @curbit <> 0
  17346.         select @curbit = @curbit * 2
  17347.     end
  17348.  
  17349.     -- SHOW THE RESULT SET
  17350.     if lower(@show_topology) <> 't' or @show_topology is null
  17351.         select name, network_name = substring(network, 1, 28),
  17352.                 status = isnull(substring(status,2,8000),''),
  17353.                 id = convert(char(4), id)
  17354.         from #spt_server order by name
  17355.     else
  17356.         select name, network_name = substring(network, 1, 28),
  17357.                 status = isnull(substring(status,2,8000),''),
  17358.                 id = convert(char(4), id), topx, topy
  17359.         from #spt_server order by name
  17360.  
  17361.     -- RETURN SUCCESS
  17362.     return(0) -- sp_helpserver
  17363. go
  17364.  
  17365. ------------------------------- sp_helpserver ---------------------------------
  17366.  
  17367. raiserror(15339,-1,-1,'sp_helplinkedsrvlogin')
  17368. go
  17369. create procedure sp_helplinkedsrvlogin
  17370.     @rmtsrvname        sysname = NULL,
  17371.     @locallogin        sysname = NULL
  17372. as
  17373.     declare    @srvid    smallint,
  17374.             @status    smallint,
  17375.             @ret    int
  17376.  
  17377.     -- CHECK REMOTE SERVER NAME.
  17378.     if @rmtsrvname is not null
  17379.     begin
  17380.         select @srvid = srvid from master.dbo.sysservers where srvname = @rmtsrvname
  17381.         if @srvid is null
  17382.         begin
  17383.         raiserror(15015,-1,-1,@rmtsrvname)
  17384.         return (1)
  17385.         end
  17386.     end
  17387.     
  17388.     -- IF SPECIFIED CHECK LOCAL USER NAME
  17389.     if (@locallogin IS NOT NULL)
  17390.     begin
  17391.         select    u.srvname as [Linked Server],        t.name as [Local Login], 
  17392.                 s.selfoutmap as [Is Self Mapping],    s.name as [Remote Login]
  17393.         from sysxlogins s, sysxlogins t, sysservers u
  17394.         where ((@rmtsrvname is null or @rmtsrvname=u.srvname) and u.srvid= s.srvid)
  17395.             and s.ishqoutmap = 1 and s.sid=t.sid 
  17396.             and t.name = @locallogin and t.ishqoutmap = 0
  17397.     end
  17398.     
  17399.     if (@locallogin IS  NULL)
  17400.     begin
  17401.         -- Get global mapping (s.sid is NULL) if any
  17402.         select    u.srvname as [Linked server],        NULL as [Local Login], 
  17403.             s.selfoutmap as [Is Self Mapping],    s.name as [Remote Login]
  17404.         from sysxlogins s, sysservers u
  17405.         where  ((@rmtsrvname is null or @rmtsrvname=u.srvname)and u.srvid= s.srvid) 
  17406.             and s.ishqoutmap = 1 and  s.sid is NULL
  17407.         UNION
  17408.         -- Get specific mappings
  17409.         select    u.srvname as [Linked server],        t.name as [Local Login],
  17410.                 s.selfoutmap as [Is Self Mapping],    s.name as [Remote Login]
  17411.         from sysxlogins s, sysxlogins t, sysservers u
  17412.         where ((@rmtsrvname is null or @rmtsrvname=u.srvname) and u.srvid= s.srvid) 
  17413.             and s.ishqoutmap = 1 and s.sid=t.sid and t.ishqoutmap = 0
  17414.         order by u.srvname
  17415.     end
  17416.     -- RETURN SUCCESS
  17417.     return(0) -- sp_helplinkedsrvlogin
  17418. go
  17419.  
  17420. -- GRANT PUBLIC ACCESS --
  17421. grant execute on sp_addlinkedserver to public
  17422. grant execute on sp_dropserver to public
  17423. grant execute on sp_serveroption to public
  17424. grant execute on sp_addserver to public
  17425. grant execute on sp_setnetname to public
  17426. grant execute on sp_helpserver to public
  17427. grant execute on sp_helplinkedsrvlogin to public
  17428. go
  17429. /************************  END-SYSSERVER-STORED-PROCS  ***********************/
  17430.  
  17431. /************************  SYSOLEDBUSERS-STORED-PROCS  ***********************/
  17432. if object_id('sp_addlinkedsrvlogin','P') IS NOT NULL
  17433.     drop procedure sp_addlinkedsrvlogin
  17434. if object_id('sp_droplinkedsrvlogin','P') IS NOT NULL
  17435.     drop procedure sp_droplinkedsrvlogin
  17436. go
  17437.  
  17438. ------------------------------- sp_addlinkedsrvlogin ---------------------------------
  17439.  
  17440. raiserror(15339,-1,-1,'sp_addlinkedsrvlogin')
  17441. go
  17442. create procedure sp_addlinkedsrvlogin
  17443.     @rmtsrvname        sysname,
  17444.     @useself        varchar(8) = 'true',
  17445.     @locallogin        sysname = NULL,
  17446.     @rmtuser        sysname = NULL,
  17447.     @rmtpassword    sysname = NULL
  17448. as
  17449.     declare    @srvid    smallint,
  17450.             @status    smallint,
  17451.             @localsid    varbinary(85),
  17452.             @ret    int
  17453.  
  17454.     -- DISALLOW USER TRANSACTION
  17455.     set implicit_transactions off
  17456.     if @@trancount > 0
  17457.     begin
  17458.         raiserror(15002,-1,-1,'sp_addlinkedsrvlogin')
  17459.         return (1)
  17460.     end
  17461.  
  17462.     -- CHECK PERMISSIONS
  17463.     if not (is_srvrolemember('securityadmin') = 1)
  17464.     begin
  17465.         raiserror(15232,-1,-1)
  17466.         return (1)
  17467.     end
  17468.  
  17469.     -- VALIDATE @useself PARAMETER --
  17470.     select @useself = lower(@useself)
  17471.     if @useself is null or @useself not in ('true','false')
  17472.     begin
  17473.         raiserror(15600,-1,-1,'sp_addlinkedsrvlogin')
  17474.         return 1
  17475.     end
  17476.         
  17477.     -- CHECK REMOTE SERVER NAME.
  17478.     select @srvid = srvid from master.dbo.sysservers where srvname = @rmtsrvname
  17479.     if @srvid is null
  17480.     begin
  17481.         raiserror(15015,-1,-1,@rmtsrvname)
  17482.         return (1)
  17483.     end
  17484.  
  17485.     -- IF SPECIFIED CHECK LOCAL USER NAME
  17486.     if (@locallogin IS NOT NULL)
  17487.     begin
  17488.         select @localsid = sid from master.dbo.syslogins where loginname = @locallogin
  17489.         if @localsid IS NULL
  17490.         begin
  17491.             -- ADD ROW FOR NT LOGIN IF NEEDED --
  17492.             execute @ret = sp_MSaddlogin_implicit_ntlogin @locallogin
  17493.             if (@ret = 0)
  17494.                 select @localsid = sid from master.dbo.syslogins where loginname = @locallogin
  17495.             if (@localsid IS NULL)
  17496.             begin
  17497.                 raiserror(15067,-1,-1,@locallogin)
  17498.                 return (1)
  17499.             end
  17500.         end
  17501.     end
  17502.  
  17503.     -- 64 IMPLIES sysxlogins::ishqoutmap is TRUE
  17504.     select @status = 64
  17505.  
  17506.     -- IF @useself IS TRUE IT OVERRIDES PARAMETERS @rmtuser, and @rmtpassword
  17507.     if @useself = 'true'
  17508.     begin
  17509.         select @rmtuser = NULL
  17510.         select @rmtpassword = NULL
  17511.         select @status = @status | 128
  17512.     end
  17513.  
  17514.     BEGIN TRAN
  17515.  
  17516.     -- DELETE EXISTING MAPPING(s) FOR THIS @sid
  17517.     update master.dbo.sysxlogins set xstatus = xstatus & ~192
  17518.         where srvid = @srvid AND ishqoutmap = 1 AND isrpcinmap = 1
  17519.             AND ((sid IS NULL AND @localsid IS NULL) OR sid = @localsid)
  17520.     if @@rowcount = 0
  17521.         delete master.dbo.sysxlogins where srvid = @srvid AND ishqoutmap = 1 
  17522.             AND ((sid IS NULL AND @localsid IS NULL) OR sid = @localsid)
  17523.  
  17524.     -- ATTEMPT TO TAG THIS ONTO EXISTING ROW --
  17525.     update master.dbo.sysxlogins
  17526.         set xstatus = (xstatus & ~192) | @status,
  17527.             xdate2 = getdate(),
  17528.             password = convert(varbinary(256), encrypt(@rmtpassword))
  17529.         where srvid = @srvid AND isrpcinmap = 1
  17530.             AND ((sid IS NULL AND @localsid IS NULL) OR sid = @localsid)
  17531.             AND ((name IS NULL AND @rmtuser IS NULL) OR name = @rmtuser)
  17532.  
  17533.     -- IF NO ROW UPDATED, INSERT NEW ROW --
  17534.     if (@@rowcount = 0)
  17535.         insert master.dbo.sysxlogins values
  17536.                 (@srvid, @localsid, @status, getdate(), getdate(), @rmtuser,
  17537.                        convert(varbinary(256), encrypt(@rmtpassword)), 0, NULL)
  17538.  
  17539.     COMMIT TRAN
  17540.  
  17541.     -- RETURN SUCCESS
  17542.     return(0) -- sp_addlinkedsrvlogin
  17543. go
  17544.  
  17545. ------------------------------- sp_droplinkedsrvlogin ---------------------------------
  17546.  
  17547. raiserror(15339,-1,-1,'sp_droplinkedsrvlogin')
  17548. go
  17549. create procedure sp_droplinkedsrvlogin
  17550.     @rmtsrvname        sysname,
  17551.     @locallogin        sysname
  17552. as
  17553.     declare @srvid    smallint
  17554.     declare @localsid    varbinary(85)
  17555.  
  17556.     -- DISALLOW USER TRANSACTION
  17557.     set implicit_transactions off
  17558.     if @@trancount > 0
  17559.     begin
  17560.         raiserror(15002,-1,-1,'sp_droplinkedsrvlogin')
  17561.         return (1)
  17562.     end
  17563.  
  17564.     -- CHECK PERMISSIONS
  17565.     if not (is_srvrolemember('securityadmin') = 1)
  17566.     begin
  17567.         raiserror(15232,-1,-1)
  17568.         return (1)
  17569.     end
  17570.     
  17571.     -- CHECK REMOTE SERVER NAME.
  17572.     select @srvid = srvid from master.dbo.sysservers where srvname = @rmtsrvname
  17573.     if @srvid is null
  17574.     begin
  17575.         raiserror(15015,-1,-1,@rmtsrvname)
  17576.         return (1)
  17577.     end
  17578.  
  17579.     -- CHECK LOCAL USER NAME IF GIVEN
  17580.     if @locallogin is not null
  17581.     begin
  17582.         select @localsid = suser_sid(@locallogin)
  17583.         if (@localsid IS NULL)
  17584.         begin
  17585.             raiserror(15067,-1,-1,@locallogin)
  17586.             return (1)
  17587.         end
  17588.     end
  17589.  
  17590.     -- DELETE MAPPING(s)
  17591.     update master.dbo.sysxlogins set xstatus = xstatus & ~192
  17592.         where srvid = @srvid AND ishqoutmap = 1 AND isrpcinmap = 1
  17593.             AND ((sid IS NULL AND @localsid IS NULL) OR sid = @localsid)
  17594.     if @@rowcount = 0
  17595.         delete master.dbo.sysxlogins where srvid = @srvid AND ishqoutmap = 1 
  17596.             AND ((sid IS NULL AND @localsid IS NULL) OR sid = @localsid)
  17597.  
  17598.     -- RETURN SUCCESS
  17599.     return(0) -- sp_droplinkedsrvlogin
  17600. go
  17601.  
  17602. -- GRANT PUBLIC ACCESS --
  17603. grant execute on sp_addlinkedsrvlogin to public
  17604. grant execute on sp_droplinkedsrvlogin to public
  17605. go
  17606. /************************  END-SYSOLEDBUSERS-STORED-PROCS  ***********************/
  17607.  
  17608. /******************************************************************************
  17609. ****************************  FULLTEXT INDEXES ********************************
  17610. ******************************************************************************/
  17611. checkpoint
  17612. go
  17613. if object_id('sp_fulltext_service','P') IS NOT NULL
  17614.     drop procedure sp_fulltext_service
  17615. if object_id('sp_fulltext_database','P') IS NOT NULL
  17616.     drop procedure sp_fulltext_database
  17617. if object_id('sp_fulltext_catalog','P') IS NOT NULL
  17618.     drop procedure sp_fulltext_catalog
  17619. if object_id('sp_fulltext_table','P') IS NOT NULL
  17620.     drop procedure sp_fulltext_table
  17621. if object_id('sp_fulltext_column','P') IS NOT NULL
  17622.     drop procedure sp_fulltext_column
  17623.     if object_id('sp_help_fulltext_catalogs','P') IS NOT NULL
  17624.     drop procedure sp_help_fulltext_catalogs
  17625. if object_id('sp_help_fulltext_catalogs_cursor','P') IS NOT NULL
  17626.     drop procedure sp_help_fulltext_catalogs_cursor
  17627. if object_id('sp_help_fulltext_tables','P') IS NOT NULL
  17628.     drop procedure sp_help_fulltext_tables
  17629. if object_id('sp_help_fulltext_tables_cursor','P') IS NOT NULL
  17630.     drop procedure sp_help_fulltext_tables_cursor
  17631. if object_id('sp_help_fulltext_columns','P') IS NOT NULL
  17632.     drop procedure sp_help_fulltext_columns
  17633. if object_id('sp_help_fulltext_columns_cursor','P') IS NOT NULL
  17634.     drop procedure sp_help_fulltext_columns_cursor
  17635. if object_id('sp_fulltext_getdata','X') IS NOT NULL
  17636.     exec sp_dropextendedproc 'sp_fulltext_getdata'
  17637. execute sp_addextendedproc 'sp_fulltext_getdata','(server internal)'
  17638. go
  17639.  
  17640.  
  17641. ---------------------------- sp_fulltext_service ------------------------------
  17642.  
  17643. raiserror(15339,-1,-1,'sp_fulltext_service')
  17644. go
  17645. create proc sp_fulltext_service
  17646.     @action        varchar(20),    -- 'resource_usage' | 'clean_up' | 'connect_timeout'
  17647.     @value        int = NULL        -- value for 'resource_usage'
  17648. as
  17649.     -- VALIDATE PARAMS --
  17650.     if @action is null OR @action not in ('resource_usage','clean_up','connect_timeout')
  17651.         OR (@value is not null AND @action not in ('resource_usage','connect_timeout'))
  17652.         OR (@value is null AND @action in ('resource_usage','connect_timeout'))
  17653.     begin
  17654.         raiserror(15600,-1,-1,'sp_fulltext_service')
  17655.         return 1
  17656.     end
  17657.  
  17658.     -- DISALLOW USER TRANSACTION --
  17659.     set implicit_transactions off
  17660.     if @@trancount > 0
  17661.     begin
  17662.         raiserror(15002,-1,-1,'sp_fulltext_service')
  17663.         return 1
  17664.     end
  17665.  
  17666.     -- CHECK PERMISSIONS (must be serveradmin) --
  17667.     if (is_srvrolemember('serveradmin') = 0)
  17668.     begin
  17669.         raiserror(15000,-1,-1)
  17670.         return 1
  17671.     end
  17672.  
  17673.     if @action = 'resource_usage'
  17674.     begin
  17675.         DBCC CALLFULLTEXT ( 9, @value )    -- FTSetResource ( @value )
  17676.         if @@error <> 0
  17677.             return 1
  17678.     end
  17679.  
  17680.     if @action = 'clean_up'
  17681.     begin
  17682.         DBCC CALLFULLTEXT ( 8 )    -- Iterate thru catalogs, remove if dbid doesn't exist.
  17683.         if @@error <> 0
  17684.             return 1
  17685.     end
  17686.  
  17687.     if @action = 'connect_timeout'
  17688.     begin
  17689.         DBCC CALLFULLTEXT ( 10, @value )    -- FTSetConnTimeout ( @value )
  17690.         if @@error <> 0
  17691.             return 1
  17692.     end
  17693.  
  17694.     -- SUCCESS --
  17695.     return 0    -- sp_fulltext_service
  17696. go
  17697.  
  17698. ---------------------------- sp_fulltext_database -----------------------------
  17699.  
  17700. raiserror(15339,-1,-1,'sp_fulltext_database')
  17701. go
  17702. create proc sp_fulltext_database
  17703.     @action        varchar(20)        -- 'enable' | 'disable'
  17704. as
  17705.     declare @ftcatid smallint,
  17706.             @path    nvarchar(260),
  17707.             @objid    int,
  17708.             @dbid    smallint
  17709.  
  17710.     -- VALIDATE PARAMS --
  17711.     if @action is null OR @action not in ('enable','disable')
  17712.     begin
  17713.         raiserror(15600,-1,-1,'sp_fulltext_database')
  17714.         return 1
  17715.     end
  17716.  
  17717.     -- DISALLOW USER TRANSACTION --
  17718.     set implicit_transactions off
  17719.     if @@trancount > 0
  17720.     begin
  17721.         raiserror(15002,-1,-1,'sp_fulltext_database')
  17722.         return 1
  17723.     end
  17724.  
  17725.     -- CHECK PERMISSIONS (must be a dbowner) --
  17726.     if (is_member('db_owner') = 0)
  17727.     begin
  17728.         raiserror(15000,-1,-1)
  17729.         return 1
  17730.     end
  17731.  
  17732.     -- CLEAR SYSDATABASES BIT AND PROPAGATE W/ CHECKPOINT (for both enable & disable) --
  17733.     select @dbid = db_id()
  17734.     update master.dbo.sysdatabases set status2 = status2 & ~536870912 where dbid = @dbid
  17735.     checkpoint
  17736.  
  17737.     -- DROP ALL CATALOGS WITH THIS DATABASE (for both enable/disable) --
  17738.     DBCC CALLFULLTEXT ( 7, @dbid )    -- FTDropAllCatalogs ( "@dbid" )
  17739.     if @@error <> 0
  17740.         return 1
  17741.  
  17742.     if @action = 'enable'
  17743.     begin
  17744.         -- CREATE CATALOGS --
  17745.         declare ftcat_crs cursor static local for select ftcatid, path from sysfulltextcatalogs
  17746.         open ftcat_crs
  17747.         fetch ftcat_crs into @ftcatid, @path
  17748.         while @@fetch_status >= 0
  17749.         begin
  17750.             DBCC CALLFULLTEXT ( 1, @ftcatid, @path )    -- FTCreateCatalog( @ftcatid, @path )
  17751.             if @@error <> 0
  17752.                 return 1
  17753.             fetch ftcat_crs into @ftcatid, @path
  17754.         end
  17755.         deallocate ftcat_crs
  17756.  
  17757.         -- ACTIVATE TABLES/URLs --
  17758.         declare ftind_crs cursor static local for select ftcatid, id from sysobjects
  17759.                     where ObjectProperty(id, 'TableHasActiveFulltextIndex') = 1
  17760.         open ftind_crs
  17761.         fetch ftind_crs into @ftcatid, @objid
  17762.         while @@fetch_status >= 0
  17763.         begin
  17764.             DBCC CALLFULLTEXT ( 5, @ftcatid, @objid )    -- FTAddURL( @ftcatid, db_id(), @objid )
  17765.             if @@error <> 0
  17766.                 return 1
  17767.             fetch ftind_crs into @ftcatid, @objid
  17768.         end
  17769.         deallocate ftind_crs
  17770.  
  17771.         -- SET SYSDATABASES BIT AND PROPAGATE W/ CHECKPOINT --
  17772.         update master.dbo.sysdatabases set status2 = status2 | 536870912 where dbid = @dbid
  17773.         checkpoint
  17774.     end
  17775.  
  17776.     -- SUCCESS --
  17777.     return 0    -- sp_fulltext_database
  17778. go
  17779.  
  17780. ---------------------------- sp_fulltext_catalog ------------------------------
  17781.  
  17782. raiserror(15339,-1,-1,'sp_fulltext_catalog')
  17783. go
  17784. create proc sp_fulltext_catalog
  17785.     @ftcat        sysname,        -- full-text catalog name
  17786.     @action        varchar(20),    -- create | drop | | rebuild | ...
  17787.     @path        nvarchar(100) = null    -- optional file path for create (max of 100 chars!!!)
  17788. as
  17789.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  17790.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  17791.     begin
  17792.         raiserror(15601,-1,-1)
  17793.         return 1
  17794.     end
  17795.  
  17796.     -- VALIDATE PARAMS --
  17797.     if @action is null
  17798.         OR @action not in ('create','drop','start_full','start_incremental','stop','rebuild')
  17799.         OR @ftcat is null OR len(@ftcat) = 0
  17800.         OR (@path is not null and @action <> 'create')
  17801.     begin
  17802.         raiserror(15600,-1,-1,'sp_fulltext_catalog')
  17803.         return 1
  17804.     end
  17805.  
  17806.     -- DISALLOW USER TRANSACTION --
  17807.     set implicit_transactions off
  17808.     if @@trancount > 0
  17809.     begin
  17810.         raiserror(15002,-1,-1,'sp_fulltext_catalog')
  17811.         return 1
  17812.     end
  17813.  
  17814.     -- CHECK PERMISSIONS (must be a dbowner) --
  17815.     if (is_member('db_owner') = 0)
  17816.     begin
  17817.         raiserror(15000,-1,-1)
  17818.         return 1
  17819.     end
  17820.  
  17821.     -- CATALOG MUST EXIST IF NOT CREATING --
  17822.     declare @ftcatid smallint
  17823.     select @ftcatid = ftcatid from sysfulltextcatalogs where name = @ftcat
  17824.     if @action <> 'create' and @ftcatid is null
  17825.     begin
  17826.         raiserror(15602,-1,-1,@ftcat)
  17827.         return 1
  17828.     end
  17829.  
  17830.     if @action = 'create'
  17831.     begin
  17832.         -- ERROR IF ALREADY THERE --
  17833.         if @ftcatid is not null
  17834.         begin
  17835.             raiserror(15603,-1,-1,@ftcat)
  17836.             return 1
  17837.         end
  17838.  
  17839.         -- GET CATID AND INSERT ROW --
  17840.         begin tran
  17841.         if not exists (select * from sysfulltextcatalogs where ftcatid = 5)
  17842.             select @ftcatid = 5
  17843.         else
  17844.             select @ftcatid = min(ftcatid+1) from sysfulltextcatalogs where 
  17845.                     (ftcatid+1) not in (select ftcatid from sysfulltextcatalogs)
  17846.         insert sysfulltextcatalogs values ( @ftcatid, @ftcat, 0, @path )
  17847.  
  17848.         -- CREATE THE CATALOG (remove row on failure)
  17849.         DBCC CALLFULLTEXT ( 1, @ftcatid, @path )    -- FTCreateCatalog( @ftcat, @path )
  17850.         if @@error <> 0
  17851.         begin
  17852.             rollback tran
  17853.             return 1
  17854.         end
  17855.         commit tran
  17856.     end
  17857.  
  17858.     if @action = 'drop'
  17859.     begin
  17860.         -- CANNOT DROP CATALOG IF USED --
  17861.         if exists (select * from sysobjects where ftcatid = @ftcatid)
  17862.         begin
  17863.             raiserror(15604,-1,-1, @ftcat)
  17864.             return 1
  17865.         end
  17866.  
  17867.         DBCC CALLFULLTEXT ( 2, @ftcatid )    -- FTDropCatalog( @ftcat )
  17868.         if @@error <> 0
  17869.             return 1
  17870.         delete sysfulltextcatalogs where ftcatid = @ftcatid
  17871.     end
  17872.  
  17873.     if @action = 'start_full'
  17874.     begin
  17875.         DBCC CALLFULLTEXT ( 3, @ftcatid, 0 )    -- FTCrawlCatalog( @ftcat, START_FULL )
  17876.         if @@error <> 0
  17877.             return 1
  17878.     end
  17879.  
  17880.     if @action = 'start_incremental'
  17881.     begin
  17882.         DBCC CALLFULLTEXT ( 3, @ftcatid, 1 )    -- FTCrawlCatalog( @ftcat, START_INCREMENTAL )
  17883.         if @@error <> 0
  17884.             return 1
  17885.     end
  17886.  
  17887.     if @action = 'stop'
  17888.     begin
  17889.         DBCC CALLFULLTEXT ( 4, @ftcatid )    -- FTCrawlCatalog( @ftcat, STOP )
  17890.         if @@error <> 0
  17891.             return 1
  17892.     end
  17893.  
  17894.     if @action = 'rebuild'
  17895.     begin
  17896.         declare @objid    int
  17897.  
  17898.         -- RE-CREATE CATALOG (Will first drop)
  17899.         select @path = path from sysfulltextcatalogs where ftcatid = @ftcatid
  17900.         DBCC CALLFULLTEXT ( 1, @ftcatid, @path )    -- FTCreateCatalog( @ftcat, @path )
  17901.         if @@error <> 0
  17902.             return 1
  17903.  
  17904.         -- RE-ACTIVATE TABLES/URLs --
  17905.         declare ftind_crs cursor static local for select id from sysobjects
  17906.                     where ftcatid = @ftcatid and ObjectProperty(id, 'TableHasActiveFulltextIndex') = 1
  17907.         open ftind_crs
  17908.         fetch ftind_crs into @objid
  17909.         while @@fetch_status >= 0
  17910.         begin
  17911.             DBCC CALLFULLTEXT ( 5, @ftcatid, @objid )    -- FTAddURL( @ftcat, db_id(), @objid )
  17912.             if @@error <> 0
  17913.                 return 1
  17914.             fetch ftind_crs into @objid
  17915.         end
  17916.         deallocate ftind_crs
  17917.     end
  17918.  
  17919.     -- SUCCESS --
  17920.     return 0    -- sp_fulltext_catalog
  17921. go
  17922.  
  17923. ----------------------------- sp_fulltext_table -------------------------------
  17924.  
  17925. raiserror(15339,-1,-1,'sp_fulltext_table')
  17926. go
  17927. create proc sp_fulltext_table
  17928.     @tabname    nvarchar(517),
  17929.     @action        varchar(20),        -- create | drop | activate | deactivate
  17930.     @ftcat        sysname = NULL,        -- create: catalog name
  17931.     @keyname    sysname = NULL        -- create: name of unique index
  17932. as
  17933.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  17934.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  17935.     begin
  17936.         raiserror(15601,-1,-1)
  17937.         return 1
  17938.     end
  17939.  
  17940.     -- VALIDATE PARAMS --
  17941.     if @action is null OR @action not in ('create','drop','activate','deactivate')
  17942.         OR (@action not in ('create') and (@ftcat is not null or @keyname is not null))
  17943.         OR (@action in ('create') and (@ftcat is null or @keyname is null))
  17944.     begin
  17945.         raiserror(15600,-1,-1,'sp_fulltext_table')
  17946.         return 1
  17947.     end
  17948.  
  17949.     -- DISALLOW USER TRANSACTION --
  17950.     set implicit_transactions off
  17951.     if @@trancount > 0
  17952.     begin
  17953.         raiserror(15002,-1,-1,'sp_fulltext_table')
  17954.         return 1
  17955.     end
  17956.  
  17957.     -- VALIDATE TABLE NAME --
  17958.     --  (1) Must exist in current database
  17959.     declare @objid int
  17960.     select @objid = object_id(@tabname, 'local')
  17961.     if @objid is null
  17962.     begin
  17963.         declare @curdbname sysname
  17964.         select @curdbname = db_name()
  17965.         raiserror(15009,-1,-1 ,@tabname, @curdbname)
  17966.         return 1
  17967.     end
  17968.     --  (2) Must be a user table (and not a temp table)
  17969.     if ObjectProperty(@objid, 'IsUserTable') = 0 OR substring(parsename(@tabname,1),1,1) = '#'
  17970.     begin
  17971.         raiserror(15218,-1,-1 ,@tabname)
  17972.         return 1
  17973.     end
  17974.  
  17975.     -- CHECK PERMISSION ON TABLE --
  17976.     if (is_member('db_owner') = 0) AND (is_member('db_ddladmin') = 0)
  17977.         AND (is_member(user_name(ObjectProperty(@objid, 'ownerid'))) = 0)
  17978.     begin
  17979.         raiserror(15219,-1,-1,@tabname)
  17980.         return 1
  17981.     end
  17982.  
  17983.     -- BEGIN TRAN AND LOCK TABLE --
  17984.     begin tran
  17985.     dbcc lockobjectschema(@tabname)
  17986.  
  17987.     -- OBTAIN CATALOG NAME FROM SYSOBJECTS & CHECK ACTION --
  17988.     declare @ftcatid smallint
  17989.     select @ftcatid = ObjectProperty(@objid, 'TableFulltextCatalogId')
  17990.     if @ftcatid <> 0 and @action = 'create'
  17991.     begin
  17992.         raiserror(15605,-1,-1,@tabname)
  17993.         goto error_abort_exit
  17994.     end
  17995.     if @ftcatid = 0 and @action <> 'create'
  17996.     begin
  17997.         raiserror(15606,-1,-1,@tabname)
  17998.         goto error_abort_exit
  17999.     end
  18000.  
  18001.     if @action = 'create'
  18002.     begin
  18003.         -- CHECK CATALOG NAME --
  18004.         select @ftcatid = null
  18005.         select @ftcatid = ftcatid from sysfulltextcatalogs where name = @ftcat
  18006.         if @ftcatid is null
  18007.         begin
  18008.             raiserror(15602,-1,-1,@ftcat)
  18009.             goto error_abort_exit
  18010.         end
  18011.  
  18012.         -- CHECK INDEX NAME (UNIQUE, SINGLE-KEY, 450-byte MAX, NON-NULLABLE) AND SET BIT IF FOUND --
  18013.         if IndexProperty(@objid, @keyname, 'IsUnique') = 1 and
  18014.            IndexProperty(@objid, @keyname, 'UserKeyCount') = 1 and
  18015.            IndexProperty(@objid, @keyname, 'IsHypothetical') = 0 and
  18016.            exists (select * from syscolumns where id = @objid and name = Index_col(@tabname, IndexProperty(@objid, @keyname, 'IndexId'), 1)
  18017.                 and length <= 450 and isnullable = 0)
  18018.         begin
  18019.             update sysindexes set status = status | 33554432 where id = @objid
  18020.                 and name = @keyname and indid > 0 and indid < 255
  18021.         end
  18022.         else
  18023.         begin
  18024.             raiserror(15607,-1,-1,@keyname)
  18025.             goto error_abort_exit
  18026.         end
  18027.  
  18028.         -- ADD CATALOG NAME TO SYSOBJECTS --
  18029.         update sysobjects set ftcatid = @ftcatid where id = @objid
  18030.     end
  18031.  
  18032.     if @action = 'drop'
  18033.     begin
  18034.         -- DROP FROM CATALOG (NO ERROR IF ALREADY DROPPED) --
  18035.         DBCC CALLFULLTEXT ( 6, @ftcatid, @objid )    -- FTDropURL( @ftcatid, db_id(), @objid )
  18036.         if @@error <> 0
  18037.             goto error_abort_exit
  18038.  
  18039.         -- REMOVE CATALOG NAME AND BITS FROM SYSTEM TABLES --
  18040.         update syscolumns set colstat = colstat & ~16 where id = @objid
  18041.         update sysindexes set status = status & ~33554432 where id = @objid
  18042.         update sysobjects set status = status & ~8, ftcatid = 0 where id = @objid
  18043.     end
  18044.  
  18045.     if @action = 'activate'
  18046.     begin
  18047.         -- ERROR IF INDEXING ALREADY ACTIVATED --
  18048.         if ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 1
  18049.         begin
  18050.             raiserror(15608,-1,-1, @tabname)
  18051.             goto error_abort_exit
  18052.         end
  18053.  
  18054.         -- MUST HAVE AT LEAST ONE COLUMN MARKED FOR FULLTEXT INDEXING --
  18055.         if not exists (select * from syscolumns where id = @objid and (colstat & 16) = 16)
  18056.         begin
  18057.             raiserror(15609,-1,-1,@tabname)
  18058.             goto error_abort_exit
  18059.         end
  18060.  
  18061.         -- ADD TO CATALOG AND SET SYSOBJECTS BIT --
  18062.         DBCC CALLFULLTEXT ( 5, @ftcatid, @objid )    -- FTAddURL( @ftcatid, db_id(), @objid )
  18063.         if @@error <> 0
  18064.             goto error_abort_exit
  18065.         update sysobjects set status = status | 8 where id = @objid
  18066.     end
  18067.  
  18068.     if @action = 'deactivate'
  18069.     begin
  18070.         -- DROP FROM CATALOG (NO ERROR IF ALREADY DROPPED) AND RESET SYSOBJECTS BIT --
  18071.         DBCC CALLFULLTEXT ( 6, @ftcatid, @objid )    -- FTDropURL( @ftcatid, db_id(), @objid )
  18072.         if @@error <> 0
  18073.             goto error_abort_exit
  18074.  
  18075.         -- TURN OFF ACTIVE BIT IN SYSOBJECTS --
  18076.         update sysobjects set status = status & ~8 where id = @objid
  18077.     end
  18078.  
  18079.     -- COMMIT TRAN --
  18080.     commit tran
  18081.     if @@error <> 0
  18082.         goto error_abort_exit
  18083.  
  18084.     -- SUCCESS --
  18085.     return 0
  18086.  
  18087. error_abort_exit:
  18088.     rollback tran
  18089.     return 1    -- sp_fulltext_table
  18090. go
  18091.  
  18092. ---------------------------- sp_fulltext_column -------------------------------
  18093.  
  18094. raiserror(15339,-1,-1,'sp_fulltext_column')
  18095. go
  18096. create proc sp_fulltext_column
  18097.     @tabname    nvarchar(517),        -- table name
  18098.     @colname    sysname,            -- column name
  18099.     @action        varchar(20)         -- add | drop
  18100. as
  18101.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  18102.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  18103.     begin
  18104.         raiserror(15601,-1,-1)
  18105.         return 1
  18106.     end
  18107.  
  18108.     -- VALIDATE PARAMS --
  18109.     if @action is null or @action not in ('add','drop')
  18110.     begin
  18111.         raiserror(15600,-1,-1,'sp_fulltext_column')
  18112.         return 1
  18113.     end
  18114.  
  18115.     -- DISALLOW USER TRANSACTION --
  18116.     set implicit_transactions off
  18117.     if @@trancount > 0
  18118.     begin
  18119.         raiserror(15002,-1,-1,'sp_fulltext_column')
  18120.         return 1
  18121.     end
  18122.  
  18123.     -- VALIDATE TABLE NAME --
  18124.     --  (1) Must exist in current database
  18125.     declare @objid int
  18126.     select @objid = object_id(@tabname, 'local')
  18127.     if @objid is null
  18128.     begin
  18129.         declare @curdbname sysname
  18130.         select @curdbname = db_name()
  18131.         raiserror(15009,-1,-1 ,@tabname, @curdbname)
  18132.         return 1
  18133.     end
  18134.     --  (2) Must be a user table
  18135.     if ObjectProperty(@objid, 'IsUserTable') = 0
  18136.     begin
  18137.         raiserror(15218,-1,-1 ,@tabname)
  18138.         return 1
  18139.     end
  18140.  
  18141.     -- CHECK PERMISSION ON TABLE --
  18142.     if (is_member('db_owner') = 0) AND (is_member('db_ddladmin') = 0)
  18143.         AND (is_member(user_name(ObjectProperty(@objid, 'ownerid'))) = 0)
  18144.     begin
  18145.         raiserror(15219,-1,-1,@tabname)
  18146.         return 1
  18147.     end
  18148.  
  18149.     -- BEGIN TRAN AND LOCK TABLE --
  18150.     begin tran
  18151.     dbcc lockobjectschema(@tabname)
  18152.  
  18153.     -- CHECK FOR CATALOG IN SYSOBJECTS --
  18154.     if ObjectProperty(@objid, 'TableFulltextCatalogId') = 0
  18155.     begin
  18156.         raiserror(15606,-1,-1,@tabname)
  18157.         goto error_abort_exit
  18158.     end
  18159.  
  18160.     -- ERROR IF FULLTEXT INDEX CURRENTLY ACTIVE --
  18161.     if ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 1
  18162.     begin
  18163.         raiserror(15610,-1,-1,@tabname)
  18164.         goto error_abort_exit
  18165.     end
  18166.  
  18167.     -- VALIDATE COLUMN NAME (CANNOT BE COMPUTED) --
  18168.     declare @typename sysname
  18169.     select @typename = type_name(ColumnProperty(@objid, @colname, 'SystemType'))
  18170.     if @typename is null OR ColumnProperty(@objid, @colname, 'IsComputed') = 1
  18171.     begin
  18172.         raiserror(15104,-1,-1,@tabname,@colname)
  18173.         goto error_abort_exit
  18174.     end
  18175.  
  18176.     if @action = 'add'
  18177.     begin
  18178.         -- VALIDATE COLUMN TYPE --
  18179.         if @typename not in (N'nchar',N'nvarchar',N'ntext',N'char',N'varchar',N'text')
  18180.         begin
  18181.             raiserror(15611,-1,-1,@colname,@tabname)
  18182.             goto error_abort_exit
  18183.         end
  18184.  
  18185.         -- SET THE BIT FOR THIS COLUMN --
  18186.         update syscolumns set colstat = colstat | 16 where id = @objid and name = @colname
  18187.     end
  18188.     else
  18189.     begin
  18190.         -- CLEAR THE BIT FOR THIS COLUMN --
  18191.         update syscolumns set colstat = colstat & ~16 where id = @objid and name = @colname
  18192.     end
  18193.  
  18194.     -- COMMIT TRAN --
  18195.     commit tran
  18196.     if @@error <> 0
  18197.         goto error_abort_exit
  18198.  
  18199.     -- SUCCESS --
  18200.     return 0
  18201.  
  18202. error_abort_exit:
  18203.     rollback tran
  18204.     return 1    -- sp_fulltext_column
  18205. go
  18206.  
  18207. ---------------------------- sp_help_fulltext_catalogs ------------------------------
  18208.  
  18209. raiserror(15339,-1,-1,'sp_help_fulltext_catalogs')
  18210. go
  18211. create proc sp_help_fulltext_catalogs
  18212.     @fulltext_catalog_name        sysname = NULL        -- full-text catalog name
  18213. as
  18214.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  18215.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  18216.     begin
  18217.         raiserror(15601,-1,-1)
  18218.         return 1
  18219.     end
  18220.  
  18221.     -- CATALOG MUST EXIST IF SPECIFIED --
  18222.     if @fulltext_catalog_name is not null
  18223.     begin
  18224.         declare @ftcatid smallint
  18225.         select @ftcatid = ftcatid from sysfulltextcatalogs where name = @fulltext_catalog_name
  18226.         if @ftcatid is null
  18227.         begin
  18228.             raiserror(15602,-1,-1,@fulltext_catalog_name)
  18229.             return 1
  18230.         end
  18231.     end
  18232.  
  18233.     -- RETRIEVE THE DEFAULT PATH --
  18234.     DECLARE @def_path as nvarchar(260)
  18235.     select @def_path = null
  18236.     exec master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
  18237.         'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer','FullTextDefaultPath',
  18238.         @def_path OUT
  18239.  
  18240.     -- SELECT ANY ROWS THAT MEET THE CRITERIA --
  18241.     select CAT.ftcatid, 
  18242.        name as NAME,
  18243.            'PATH'= CASE WHEN path is NULL THEN @def_path 
  18244.                         ELSE path
  18245.                         END,
  18246.            FullTextCatalogProperty(CAT.name, 'PopulateStatus') AS STATUS ,
  18247.            (select COUNT(*) 
  18248.               from sysobjects 
  18249.               where type='U' and sysobjects.ftcatid = CAT.ftcatid
  18250.            ) as NUMBER_FULLTEXT_TABLES
  18251.     from sysfulltextcatalogs as CAT
  18252.     where ( @fulltext_catalog_name is null or name = @fulltext_catalog_name )
  18253.     order by ftcatid
  18254.  
  18255.     -- SUCCESS --
  18256.     return 0    -- sp_help_fulltext_catalogs
  18257. go
  18258.  
  18259. ---------------------------- sp_help_fulltext_catalogs_cursor ------------------------------
  18260.  
  18261. raiserror(15339,-1,-1,'sp_help_fulltext_catalogs_cursor')
  18262. go
  18263. create proc sp_help_fulltext_catalogs_cursor
  18264.     @cursor_return CURSOR VARYING OUTPUT,
  18265.     @fulltext_catalog_name        sysname = NULL        -- full-text catalog name
  18266. as
  18267.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  18268.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  18269.     begin
  18270.         raiserror(15601,-1,-1)
  18271.         return 1
  18272.     end
  18273.  
  18274.     -- CATALOG MUST EXIST IF SPECIFIED --
  18275.     if @fulltext_catalog_name is not null
  18276.     begin
  18277.         declare @ftcatid smallint
  18278.         select @ftcatid = ftcatid from sysfulltextcatalogs where name = @fulltext_catalog_name
  18279.         if @ftcatid is null
  18280.         begin
  18281.             raiserror(15602,-1,-1,@fulltext_catalog_name)
  18282.             return 1
  18283.         end
  18284.     end
  18285.  
  18286.     -- RETRIEVE THE DEFAULT PATH --
  18287.     DECLARE @def_path as nvarchar(260)
  18288.     select @def_path = null
  18289.     exec master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
  18290.         'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer','FullTextDefaultPath',
  18291.         @def_path OUT
  18292.  
  18293.     -- SELECT ANY ROWS THAT MEET THE CRITERIA --
  18294.     set @cursor_return =      CURSOR LOCAL SCROLL DYNAMIC FOR 
  18295.     select CAT.ftcatid, 
  18296.        name as NAME,
  18297.        'PATH'= CASE WHEN path is NULL THEN @def_path 
  18298.                             ELSE path
  18299.                             END,
  18300.         FullTextCatalogProperty(CAT.name, 'PopulateStatus') AS STATUS ,
  18301.         (select COUNT(*) 
  18302.          from sysobjects 
  18303.          where type='U' and sysobjects.ftcatid = CAT.ftcatid
  18304.          ) as NUMBER_FULLTEXT_TABLES
  18305.         from sysfulltextcatalogs as CAT
  18306.         where ( @fulltext_catalog_name is null or name = @fulltext_catalog_name )
  18307.         order by ftcatid
  18308.  
  18309.     open @cursor_return
  18310.  
  18311.     -- SUCCESS --
  18312.     return 0    -- sp_help_fulltext_catalogs_cursor
  18313. go
  18314.  
  18315. ---------------------------- sp_help_fulltext_tables ------------------------------
  18316.  
  18317. raiserror(15339,-1,-1,'sp_help_fulltext_tables')
  18318. go
  18319. create proc sp_help_fulltext_tables
  18320.     @fulltext_catalog_name        sysname = NULL,            -- full-text catalog name
  18321.     @table_name    nvarchar(517) = NULL    -- table name
  18322. as
  18323.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  18324.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  18325.     begin
  18326.         raiserror(15601,-1,-1)
  18327.         return 1
  18328.     end
  18329.  
  18330.     -- CATALOG MUST EXIST IF SPECIFIED --
  18331.     declare @ftcatid smallint
  18332.     if @fulltext_catalog_name is not null
  18333.     begin
  18334.         select @ftcatid = ftcatid from sysfulltextcatalogs where name = @fulltext_catalog_name
  18335.         if @ftcatid is null
  18336.         begin
  18337.             raiserror(15602,-1,-1,@fulltext_catalog_name)
  18338.             return 1
  18339.         end
  18340.     end
  18341.  
  18342.     if @table_name is not null
  18343.     begin
  18344.         -- VALIDATE TABLE NAME --
  18345.         --  (1) Must exist in current database
  18346.         declare @objid int
  18347.         select @objid = object_id(@table_name, 'local')
  18348.         if @objid is null
  18349.         begin
  18350.             declare @curdbname sysname
  18351.             select @curdbname = db_name()
  18352.             raiserror(15009,-1,-1 ,@table_name, @curdbname)
  18353.             return 1
  18354.         end
  18355.         --  (2) Must be a user table (and not a temp table)
  18356.         if ObjectProperty(@objid, 'IsUserTable') = 0 OR substring(parsename(@table_name,1),1,1) = '#'
  18357.         begin
  18358.             raiserror(15218,-1,-1 ,@table_name)
  18359.             return 1
  18360.         end
  18361.     end
  18362.     
  18363.     select susr.name as TABLE_OWNER, sobj.name as TABLE_NAME, 
  18364.         sdex.name as FULLTEXT_KEY_INDEX_NAME, 
  18365.         ObjectProperty(sobj.id, 'TableFulltextKeyColumn') as FULLTEXT_KEY_COLID, 
  18366.         ObjectProperty(sobj.id, 'TableHasActiveFulltextIndex') as FULLTEXT_INDEX_ACTIVE, 
  18367.         scat.name as FULLTEXT_CATALOG_NAME 
  18368.         from sysobjects as sobj, sysindexes as sdex, sysusers as susr, sysfulltextcatalogs as scat
  18369.         where(  
  18370.                 @fulltext_catalog_name is null or
  18371.                 sobj.ftcatid = @ftcatid
  18372.              ) and
  18373.              (
  18374.                 @table_name is null or
  18375.                   sobj.id = @objid
  18376.              ) and
  18377.               sobj.uid = susr.uid and 
  18378.               sobj.ftcatid = scat.ftcatid and
  18379.               sdex.status & 33554432 <> 0 and   /* means that this is the index used enforce
  18380.                                                    the uniqueness of the full-text key column */
  18381.               sdex.id = sobj.id
  18382.         order by TABLE_OWNER, TABLE_NAME
  18383.  
  18384.     -- SUCCESS --
  18385.     return 0    -- sp_help_fulltext_tables
  18386. go
  18387.  
  18388. ---------------------------- sp_help_fulltext_tables_cursor ------------------------------
  18389. raiserror(15339,-1,-1,'sp_help_fulltext_tables_cursor')
  18390. go
  18391. create proc sp_help_fulltext_tables_cursor
  18392.     @cursor_return CURSOR VARYING OUTPUT,
  18393.     @fulltext_catalog_name        sysname = NULL,            -- full-text catalog name
  18394.     @table_name    nvarchar(517) = NULL    -- table name
  18395. as
  18396.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  18397.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  18398.     begin
  18399.         raiserror(15601,-1,-1)
  18400.         return 1
  18401.     end
  18402.  
  18403.     -- CATALOG MUST EXIST IF SPECIFIED --
  18404.     declare @ftcatid smallint
  18405.     if @fulltext_catalog_name is not null
  18406.     begin
  18407.         select @ftcatid = ftcatid from sysfulltextcatalogs where name = @fulltext_catalog_name
  18408.         if @ftcatid is null
  18409.         begin
  18410.             raiserror(15602,-1,-1,@fulltext_catalog_name)
  18411.             return 1
  18412.         end
  18413.     end
  18414.  
  18415.     if @table_name is not null
  18416.     begin
  18417.         -- VALIDATE TABLE NAME --
  18418.         --  (1) Must exist in current database
  18419.         declare @objid int
  18420.         select @objid = object_id(@table_name, 'local')
  18421.         if @objid is null
  18422.         begin
  18423.             declare @curdbname sysname
  18424.             select @curdbname = db_name()
  18425.             raiserror(15009,-1,-1 ,@table_name, @curdbname)
  18426.             return 1
  18427.         end
  18428.         --  (2) Must be a user table (and not a temp table)
  18429.         if ObjectProperty(@objid, 'IsUserTable') = 0 
  18430.                          OR substring(parsename(@table_name,1),1,1) = '#'
  18431.         begin
  18432.             raiserror(15218,-1,-1 ,@table_name)
  18433.             return 1
  18434.         end
  18435.     end
  18436.     
  18437.     set @cursor_return =      CURSOR LOCAL SCROLL DYNAMIC FOR 
  18438.     select susr.name as TABLE_OWNER, sobj.name as TABLE_NAME, 
  18439.         sdex.name as FULLTEXT_KEY_INDEX_NAME, 
  18440.         ObjectProperty(sobj.id, 'TableFulltextKeyColumn') as FULLTEXT_KEY_COLID, 
  18441.         ObjectProperty(sobj.id, 'TableHasActiveFulltextIndex') as FULLTEXT_INDEX_ACTIVE, 
  18442.         scat.name as FULLTEXT_CATALOG_NAME 
  18443.         from sysobjects as sobj, sysindexes as sdex, sysusers as susr, sysfulltextcatalogs as scat
  18444.         where(  
  18445.                 @fulltext_catalog_name is null or
  18446.                 sobj.ftcatid = @ftcatid
  18447.              ) and
  18448.              (
  18449.                 @table_name is null or
  18450.                   sobj.id = @objid
  18451.              ) and
  18452.               sobj.uid = susr.uid and 
  18453.               sobj.ftcatid = scat.ftcatid and
  18454.               sdex.status & 33554432 <> 0 and   /* means that this is the index used enforce
  18455.                                                    the uniqueness of the full-text key column */
  18456.               sdex.id = sobj.id
  18457.         order by TABLE_OWNER, TABLE_NAME
  18458.  
  18459.     open @cursor_return
  18460.  
  18461.     -- SUCCESS --
  18462.     return 0    -- sp_help_fulltext_tables_cursor
  18463. go
  18464.  
  18465. ---------------------------- sp_help_fulltext_columns ------------------------------
  18466. raiserror(15339,-1,-1,'sp_help_fulltext_columns')
  18467. go
  18468. create proc sp_help_fulltext_columns
  18469.     @table_name    nvarchar(517) = NULL,        -- table name
  18470.     @column_name    sysname = NULL                -- column name
  18471. as
  18472.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  18473.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  18474.     begin
  18475.         raiserror(15601,-1,-1)
  18476.         return 1
  18477.     end
  18478.  
  18479.     if @table_name is not null
  18480.     begin
  18481.         -- VALIDATE TABLE NAME --
  18482.         --  (1) Must exist in current database
  18483.         declare @objid int
  18484.         select @objid = object_id(@table_name, 'local')
  18485.         if @objid is null
  18486.         begin
  18487.             declare @curdbname sysname
  18488.             select @curdbname = db_name()
  18489.             raiserror(15009,-1,-1 ,@table_name, @curdbname)
  18490.             return 1
  18491.         end
  18492.         --  (2) Must be a user table (and not a temp table)
  18493.         if ObjectProperty(@objid, 'IsUserTable') = 0 
  18494.                              OR substring(parsename(@table_name,1),1,1) = '#'
  18495.         begin
  18496.             raiserror(15218,-1,-1 ,@table_name)
  18497.             return 1
  18498.         end
  18499.  
  18500.         -- VALIDATE COLUMN NAME (CANNOT BE COMPUTED) --
  18501.         if @column_name is not null
  18502.         begin
  18503.             declare @typename sysname
  18504.             select @typename = type_name(ColumnProperty(@objid, @column_name, 'SystemType'))
  18505.             if @typename is null OR ColumnProperty(@objid, @column_name, 'IsComputed') = 1
  18506.             begin
  18507.                 raiserror(15104,-1,-1,@table_name,@column_name)
  18508.                 return 1
  18509.             end
  18510.         end
  18511.  
  18512.     end
  18513.     
  18514.     select susr.name as TABLE_OWNER, sobj.name as TABLE_NAME, 
  18515.         scol.colid as FULLTEXT_COLID, 
  18516.         scol.name as FULLTEXT_COLUMN_NAME
  18517.         from sysobjects as sobj, sysusers as susr, syscolumns as scol
  18518.         where ( 
  18519.                 @table_name is null or
  18520.                 sobj.id = @objid
  18521.               ) and 
  18522.               scol.id = sobj.id and
  18523.               sobj.uid = susr.uid and 
  18524.               (      
  18525.                   @column_name is null or
  18526.                   scol.name = @column_name
  18527.               ) and
  18528.               ColumnProperty(sobj.id, scol.name, 'IsFullTextIndexed') = 1
  18529.         order by TABLE_OWNER, TABLE_NAME, FULLTEXT_COLID
  18530.  
  18531.     -- SUCCESS --
  18532.     return 0    -- sp_help_fulltext_columns
  18533. go
  18534.  
  18535. ---------------------------- sp_help_fulltext_columns_cursor ------------------------------
  18536. raiserror(15339,-1,-1,'sp_help_fulltext_columns_cursor')
  18537. go
  18538. create proc sp_help_fulltext_columns_cursor
  18539.     @cursor_return CURSOR VARYING OUTPUT,
  18540.     @table_name    nvarchar(517) = NULL,        -- table name
  18541.     @column_name    sysname = NULL                -- column name
  18542. as
  18543.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  18544.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  18545.     begin
  18546.         raiserror(15601,-1,-1)
  18547.         return 1
  18548.     end
  18549.  
  18550.     if @table_name is not null
  18551.     begin
  18552.         -- VALIDATE TABLE NAME --
  18553.         --  (1) Must exist in current database
  18554.         declare @objid int
  18555.         select @objid = object_id(@table_name, 'local')
  18556.         if @objid is null
  18557.         begin
  18558.             declare @curdbname sysname
  18559.             select @curdbname = db_name()
  18560.             raiserror(15009,-1,-1 ,@table_name, @curdbname)
  18561.             return 1
  18562.         end
  18563.         --  (2) Must be a user table (and not a temp table)
  18564.         if ObjectProperty(@objid, 'IsUserTable') = 0 
  18565.                                  OR substring(parsename(@table_name,1),1,1) = '#'
  18566.         begin
  18567.             raiserror(15218,-1,-1 ,@table_name)
  18568.             return 1
  18569.         end
  18570.  
  18571.         -- VALIDATE COLUMN NAME (CANNOT BE COMPUTED) --
  18572.         if @column_name is not null
  18573.         begin
  18574.             declare @typename sysname
  18575.             select @typename = type_name(ColumnProperty(@objid, @column_name, 'SystemType'))
  18576.             if @typename is null OR ColumnProperty(@objid, @column_name, 'IsComputed') = 1
  18577.             begin
  18578.                 raiserror(15104,-1,-1,@table_name,@column_name)
  18579.                 return 1
  18580.             end
  18581.         end
  18582.     end
  18583.     
  18584.     set @cursor_return =      CURSOR LOCAL SCROLL DYNAMIC FOR 
  18585.         select susr.name as TABLE_OWNER, sobj.name as TABLE_NAME, 
  18586.             scol.colid as FULLTEXT_COLID, 
  18587.             scol.name as FULLTEXT_COLUMN_NAME
  18588.             from sysobjects as sobj, sysusers as susr, syscolumns as scol
  18589.             where ( 
  18590.                     @table_name is null or
  18591.                     sobj.id = @objid
  18592.                   ) and 
  18593.                   scol.id = sobj.id and
  18594.                   sobj.uid = susr.uid and 
  18595.                   (      
  18596.                       @column_name is null or
  18597.                       scol.name = @column_name
  18598.                   ) and
  18599.                   ColumnProperty(sobj.id, scol.name, 'IsFullTextIndexed') = 1
  18600.             order by TABLE_OWNER, TABLE_NAME, FULLTEXT_COLID
  18601.  
  18602.     open @cursor_return
  18603.  
  18604.     -- SUCCESS --
  18605.     return 0    -- sp_help_fulltext_columns_cursor
  18606. go
  18607.  
  18608. -- GRANT PUBLIC ACCESS --
  18609. grant execute on sp_fulltext_service to public
  18610. grant execute on sp_fulltext_database to public
  18611. grant execute on sp_fulltext_catalog to public
  18612. grant execute on sp_fulltext_table to public
  18613. grant execute on sp_fulltext_column to public
  18614. grant execute on sp_help_fulltext_catalogs to public
  18615. grant execute on sp_help_fulltext_catalogs_cursor to public
  18616. grant execute on sp_help_fulltext_tables  to public
  18617. grant execute on sp_help_fulltext_tables_cursor  to public
  18618. grant execute on sp_help_fulltext_columns  to public
  18619. grant execute on sp_help_fulltext_columns_cursor  to public
  18620. -- sp_fulltext_getdata is NOT for CUSTOMER USE! (do not doc)
  18621. go
  18622.  
  18623. /*************************  END FULLTEXT INDEXES *****************************/
  18624.  
  18625. checkpoint
  18626. go
  18627. if object_id('sp_describe_cursor','P') IS NOT NULL
  18628.     drop procedure sp_describe_cursor
  18629. if object_id('sp_describe_cursor_columns','P') IS NOT NULL
  18630.     drop procedure sp_describe_cursor_columns
  18631. if object_id('sp_describe_cursor_tables','P') IS NOT NULL
  18632.     drop procedure sp_describe_cursor_tables
  18633. if object_id('sp_cursor_list','P') IS NOT NULL
  18634.     drop procedure sp_cursor_list
  18635. go
  18636.  
  18637. raiserror(15339,-1,-1,'sp_describe_cursor')
  18638. go
  18639. -- Creation of sp_describe_cursor 
  18640.  
  18641. Create Procedure sp_describe_cursor 
  18642. (  @cursor_return CURSOR VARYING OUTPUT,
  18643.    @cursor_source nvarchar (30),
  18644.    @cursor_identity nvarchar (128)
  18645. )
  18646. AS
  18647.  
  18648. declare @scope int
  18649.  
  18650. /* Check if the cursor exists by name or handle. */
  18651. If cursor_status ( @cursor_source, @cursor_identity ) >= -1
  18652. begin
  18653.     if lower(convert(varchar(30), @cursor_source)) = 'local' OR 
  18654.         lower(convert(varchar(128), @cursor_source)) = 'variable'
  18655.         select @scope = 1
  18656.     else
  18657.     if lower(convert(varchar(30), @cursor_source)) = 'global'
  18658.         select @scope = 2
  18659.  
  18660.  
  18661.     set @cursor_return =  CURSOR LOCAL SCROLL DYNAMIC FOR 
  18662.                     SELECT reference_name, cursor_name, cursor_scope, 
  18663.                     status, model, concurrency, scrollable,
  18664.                     open_status, cursor_rows, fetch_status,
  18665.                     column_count, row_count, last_operation,
  18666.                     cursor_handle
  18667.                     FROM master.dbo.syscursorrefs scr, master.dbo.syscursors sc
  18668.                     WHERE     scr.cursor_scope = @scope and 
  18669.                       scr.reference_name = @cursor_identity and 
  18670.                       scr.cursor_handl = sc.cursor_handle
  18671.                 ORDER BY 3, 1
  18672.                 FOR READ ONLY
  18673.     open @cursor_return
  18674.         
  18675. end
  18676. go
  18677.  
  18678. raiserror(15339,-1,-1,'sp_describe_cursor_columns')
  18679. go
  18680. -- Creation of sp_describe_cursor_columns
  18681.  
  18682. Create Procedure sp_describe_cursor_columns 
  18683. (  @cursor_return CURSOR VARYING OUTPUT,
  18684.    @cursor_source nvarchar (30),
  18685.    @cursor_identity nvarchar (128)
  18686. )
  18687. AS
  18688.  
  18689. declare @scope int
  18690.  
  18691. /* Check if the cursor exists by name or handle. */
  18692. If cursor_status ( @cursor_source, @cursor_identity ) >= -1
  18693. begin
  18694.     if lower(convert(varchar(30), @cursor_source)) = 'local' OR 
  18695.         lower(convert(varchar(128), @cursor_source)) = 'variable'
  18696.         select @scope = 1
  18697.     else
  18698.     if lower(convert(varchar(30), @cursor_source)) = 'global'
  18699.         select @scope = 2
  18700.  
  18701.     set @cursor_return =      CURSOR LOCAL SCROLL DYNAMIC FOR 
  18702.                 SELECT column_name, ordinal_position, column_characteristics_flags,
  18703.                     column_size, data_type_sql, column_precision,
  18704.                     column_scale, order_position, order_direction,
  18705.                     hidden_column, columnid, objectid, dbid, dbname
  18706.                 FROM master.dbo.syscursorrefs scr, master.dbo.syscursorcolumns scc
  18707.                 WHERE     scr.cursor_scope = @scope and 
  18708.                     scr.reference_name = @cursor_identity and 
  18709.                     scr.cursor_handl = scc.cursor_handle
  18710.                 ORDER BY 2
  18711.                 FOR READ ONLY
  18712.     open @cursor_return        
  18713.         
  18714. end
  18715. go
  18716.  
  18717. raiserror(15339,-1,-1,'sp_describe_cursor_tables')
  18718. go
  18719. -- Creation of sp_describe_cursor_tables
  18720.  
  18721. Create Procedure sp_describe_cursor_tables
  18722. (  @cursor_return CURSOR VARYING OUTPUT,
  18723.    @cursor_source nvarchar (30),
  18724.    @cursor_identity nvarchar (128)
  18725. )
  18726. AS
  18727.  
  18728. declare @scope int
  18729.  
  18730. /* Check if the cursor exists by name or handle. */
  18731. If cursor_status ( @cursor_source, @cursor_identity ) >= -1
  18732. begin
  18733.     if lower(convert(varchar(30), @cursor_source)) = 'local' OR 
  18734.         lower(convert(varchar(128), @cursor_source)) = 'variable'
  18735.         select @scope = 1
  18736.     else
  18737.     if lower(convert(varchar(30), @cursor_source)) = 'global'
  18738.         select @scope = 2
  18739.     
  18740.     set @cursor_return =      CURSOR LOCAL SCROLL DYNAMIC FOR 
  18741.                 SELECT table_owner, table_name, optimizer_hint, lock_type, server_name, objectid, dbid, dbname
  18742.                 FROM master.dbo.syscursorrefs scr, master.dbo.syscursortables sct
  18743.                 WHERE     scr.cursor_scope = @scope and 
  18744.                     scr.reference_name = @cursor_identity and 
  18745.                     scr.cursor_handl = sct.cursor_handle
  18746.                 FOR READ ONLY
  18747.     open @cursor_return
  18748. end
  18749. go
  18750.  
  18751. raiserror(15339,-1,-1,'sp_cursor_list')
  18752. go
  18753. -- Creation of sp_cursor_list
  18754.  
  18755. create procedure sp_cursor_list
  18756.    @cursor_return CURSOR VARYING OUTPUT,
  18757.    @cursor_scope int
  18758. )
  18759. AS
  18760.  
  18761. if (@cursor_scope < 1) OR (@cursor_scope > 3)
  18762.     begin
  18763.         /* Raise an error: ?The value of parameter  is invalid? */
  18764.         raiserror ( 16902, 1, 1,N'sp_cursor_list', N'@cursor_scope')
  18765.         return (1)
  18766.     end
  18767.  
  18768. if ( @cursor_scope  < 3)
  18769. begin
  18770.     set @cursor_return =  CURSOR LOCAL SCROLL DYNAMIC FOR 
  18771.                     SELECT reference_name, cursor_name, cursor_scope, 
  18772.                     status, model, concurrency, scrollable,
  18773.                     open_status, cursor_rows, fetch_status,
  18774.                     column_count, row_count, last_operation,
  18775.                     cursor_handle
  18776.                 FROM master.dbo.syscursorrefs scr, master.dbo.syscursors sc
  18777.                 WHERE     scr.cursor_scope = @cursor_scope AND 
  18778.                     scr.cursor_handl = sc.cursor_handle
  18779.                 FOR READ ONLY
  18780. end
  18781. else
  18782. begin
  18783.     set @cursor_return =  CURSOR LOCAL SCROLL DYNAMIC FOR 
  18784.                     SELECT reference_name, cursor_name, cursor_scope, 
  18785.                     status, model, concurrency, scrollable,
  18786.                     open_status, cursor_rows, fetch_status,
  18787.                     column_count, row_count, last_operation,
  18788.                     cursor_handle
  18789.                 FROM master.dbo.syscursorrefs scr, master.dbo.syscursors sc
  18790.                 WHERE scr.cursor_handl = sc.cursor_handle
  18791.                 FOR READ ONLY
  18792. end
  18793. open @cursor_return
  18794. go
  18795.  
  18796. /************************  END-CURSORINFO-STORED-PROCS  ***********************/
  18797.  
  18798. -- GRANT PUBLIC ACCESS --
  18799. grant execute on sp_describe_cursor to public
  18800. grant execute on sp_describe_cursor_columns to public
  18801. grant execute on sp_describe_cursor_tables to public
  18802. grant execute on sp_cursor_list to public
  18803. go
  18804.  
  18805. checkpoint
  18806. go
  18807.  
  18808. print ' '
  18809. print 'Granting privileges on system tables.'
  18810. go
  18811.  
  18812. grant select on sysalternates to public
  18813. grant select on syscharsets to public
  18814. grant select on syscolumns to public
  18815. grant select on syscomments to public
  18816. grant select on sysconfigures to public
  18817. grant select on sysdatabases to public
  18818. grant select on sysdepends to public
  18819. grant select on sysdevices to public
  18820. grant select on sysindexes to public
  18821. grant select on syslanguages to public
  18822. go
  18823.  
  18824.  
  18825. checkpoint
  18826. go
  18827.  
  18828. grant select on sysmessages to public
  18829. grant select on sysobjects to public
  18830. grant select on sysprotects to public
  18831. grant select on syspermissions to public
  18832. grant select on syssegments to public
  18833. grant select on sysservers to public
  18834. grant select on systypes to public
  18835. grant select on sysusers to public
  18836. grant select on sysreferences to public
  18837. grant select on sysfiles to public
  18838. grant select on sysfilegroups to public
  18839. grant select on sysfulltextcatalogs to public
  18840. go
  18841.  
  18842.  
  18843. checkpoint
  18844. go
  18845.  
  18846. print ' '
  18847. print 'Granting privileges on system stored procedures'
  18848. go
  18849.  
  18850. grant execute on MS_sqlctrs_users to public
  18851. go
  18852.  
  18853. grant execute on sp_user_counter1   to public
  18854. grant execute on sp_user_counter2   to public
  18855. grant execute on sp_user_counter3   to public
  18856. grant execute on sp_user_counter4   to public
  18857. grant execute on sp_user_counter5   to public
  18858. grant execute on sp_user_counter6   to public
  18859. grant execute on sp_user_counter7   to public
  18860. grant execute on sp_user_counter8   to public
  18861. grant execute on sp_user_counter9   to public
  18862. grant execute on sp_user_counter10  to public
  18863.  
  18864. checkpoint
  18865. go
  18866.  
  18867. grant execute on sp_addmessage to public
  18868. grant execute on sp_addumpdevice to public
  18869. grant execute on sp_addtype to public
  18870. grant execute on sp_altermessage to public
  18871. grant execute on sp_bindefault to public
  18872. grant execute on sp_bindrule to public
  18873. grant execute on sp_checknames to public
  18874. grant execute on sp_configure to public
  18875. grant execute on sp_cursor to public
  18876. grant execute on sp_cursorclose to public
  18877. grant execute on sp_cursorfetch to public
  18878. grant execute on sp_cursoropen to public
  18879. grant execute on sp_cursoroption to public
  18880. grant execute on sp_dboption to public
  18881. grant execute on sp_bindsession to public
  18882. grant execute on sp_getbindtoken to public
  18883. grant execute on sp_dbcmptlevel to public
  18884. grant execute on sp_executesql to public
  18885. grant execute on sp_prepare to public
  18886. grant execute on sp_execute to public
  18887. grant execute on sp_unprepare to public
  18888. grant execute on sp_cursorprepare to public
  18889. grant execute on sp_cursorexecute to public
  18890. grant execute on sp_cursorunprepare to public
  18891. grant execute on sp_createorphan to public
  18892. grant execute on sp_droporphans to public
  18893. grant execute on sp_reset_connection to public
  18894. go
  18895.  
  18896. checkpoint
  18897. go
  18898.  
  18899. grant execute on sp_depends to public
  18900. grant execute on sp_dropmessage to public
  18901. grant execute on sp_droptype to public
  18902. go
  18903. grant execute on sp_help to public
  18904. grant execute on sp_helpconstraint to public
  18905. grant execute on sp_helpdb to public
  18906. grant execute on sp_helpfile to public
  18907. grant execute on sp_helpfilegroup to public
  18908. grant execute on sp_helpdevice to public
  18909. grant execute on sp_helpextendedproc to public
  18910. grant execute on sp_helpgroup to public
  18911. grant execute on sp_helpindex to public
  18912. grant execute on sp_helplanguage to public
  18913. grant execute on sp_helplog to public
  18914. grant execute on sp_helplogins to public
  18915. grant execute on sp_helpremotelogin to public
  18916. grant execute on sp_helprotect to public
  18917. grant execute on sp_helpsort to public
  18918. grant execute on sp_helpsql to public
  18919. grant execute on sp_helptext to public
  18920. grant execute on sp_helpuser to public
  18921. grant execute on sp_lock to public
  18922. go
  18923.  
  18924. checkpoint
  18925. go
  18926.  
  18927. grant execute on sp_objectfilegroup to public
  18928. grant execute on sp_procoption to public
  18929. grant execute on sp_recompile to public
  18930. grant execute on sp_remoteoption to public
  18931. grant execute on sp_rename to public
  18932. grant execute on sp_renamedb to public
  18933. grant execute on sp_spaceused to public
  18934. grant execute on sp_checkdbtempsize to public
  18935. grant execute on sp_checktabletempsize to public
  18936. grant execute on sp_sqlexec to public
  18937. go
  18938.  
  18939. grant execute on sp_blockcnt to public
  18940. grant execute on sp_tableoption to public
  18941. grant execute on sp_indexoption to public
  18942. grant execute on sp_tempdbspace to public
  18943. go
  18944.  
  18945. grant execute on sp_unbindefault to public
  18946. grant execute on sp_unbindrule to public
  18947. grant execute on sp_validname to public
  18948. grant execute on sp_validlang to public
  18949. grant execute on sp_who to public
  18950. grant execute on sp_who2 to public
  18951. grant execute on sp_updatestats to public
  18952. grant execute on sp_createstats to public
  18953. grant execute on sp_autostats to public
  18954. grant execute on sp_helptrigger to public
  18955. go
  18956.  
  18957. grant execute on sp_MSget_current_activity to public
  18958. grant execute on sp_MSset_current_activity to public
  18959. go
  18960.  
  18961. checkpoint
  18962. go
  18963.  
  18964. print ' '
  18965. print 'Granting privileges on extended stored procedures'
  18966. go
  18967.  
  18968. grant execute on xp_sprintf to public
  18969. grant execute on xp_sscanf to public
  18970. grant execute on xp_unc_to_drive to public
  18971. grant execute on xp_msver to public
  18972. go
  18973.  
  18974. print ' '
  18975. print 'Granting privileges on objects in model database.'
  18976. go
  18977. use model
  18978. go
  18979. grant select on sysconstraints to public
  18980. grant select on sysalternates to public
  18981. grant select on syscolumns to public
  18982. grant select on syscomments to public
  18983. grant select on sysdepends to public
  18984. grant select on sysindexes to public
  18985. grant select on sysobjects to public
  18986. grant select on sysprotects to public
  18987. grant select on syspermissions to public
  18988. grant select on syssegments to public
  18989. grant select on systypes to public
  18990. grant select on sysusers to public
  18991. grant select on sysreferences to public
  18992. grant select on sysfiles to public
  18993. grant select on sysfilegroups to public
  18994. grant select on sysfulltextcatalogs to public
  18995. go
  18996.  
  18997. use master
  18998. go
  18999.  
  19000. checkpoint
  19001. go
  19002.  
  19003. /*
  19004. ** Set some things now that sp_configure has been created.
  19005. */
  19006. print ' '
  19007. print 'Making final database configuration settings.'
  19008. go
  19009.  
  19010.  
  19011. declare @i varchar(255)
  19012.  
  19013. exec master.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
  19014.      'SOFTWARE\Microsoft\MSSQLServer\Setup', 'SetupStatus',
  19015.       @i out
  19016.  
  19017. print ' '
  19018.  
  19019. if isnull(lower(@i),'null') not in ('upgrade','installed')    -- That key will only exist during an upgrade.
  19020.     begin -- NewInstall
  19021.         select 'Will leave database size config=111 alone at',value from sysconfigures where config=111
  19022.  
  19023. --        print 'Setting default database size to 1 Meg.'
  19024. --        exec sp_configure 'database size',1
  19025.     end
  19026. else
  19027.         begin
  19028.             select 'Re-Initializing free buffer setting, from....',value from sysconfigures where config=1515
  19029.             update sysconfigures set value =
  19030.                 (select value/20 from sysconfigures
  19031.                     where config = 104)
  19032.                 where config = 1515 --- ?!?! in ProcSyst?
  19033.         end
  19034. go
  19035. print 'Forcing config for remote access to 1'
  19036. exec sp_configure 'remote access',1
  19037. go
  19038.  
  19039. exec sp_MS_upd_sysobj_category 2  --Now do catalog updates.
  19040.  
  19041. go
  19042.  
  19043. --- Enable auto-create and update of statistics
  19044. exec sp_dboption 'tempdb', 'auto create statistics', 'on'
  19045. exec sp_dboption 'master', 'auto create statistics', 'on'
  19046. exec sp_dboption 'model', 'auto create statistics', 'on'
  19047.  
  19048. exec sp_dboption 'tempdb', 'auto update statistics', 'on'
  19049. exec sp_dboption 'master', 'auto update statistics', 'on'
  19050. exec sp_dboption 'model', 'auto update statistics', 'on'
  19051. go
  19052.  
  19053. exec sp_dboption 'master','trunc. log on chkpt.','true'
  19054. go
  19055. exec sp_configure 'allow updates',0
  19056. reconfigure with override
  19057.  
  19058. print ' '
  19059. -- print 'Checking objects created by ProcSyst.SQL ....'
  19060. go
  19061.  
  19062. declare @vdt varchar(99)
  19063. select  @vdt = convert(varchar,getdate(),113)
  19064. raiserror('Finishing Install\ProcSyst.SQL at  %s',0,1,@vdt)
  19065. go
  19066.  
  19067. checkpoint
  19068. go
  19069. -- - -----
  19070.  
  19071. -- test
  19072. -- junk
  19073.